2009-06-22 38 views
5

我重写我的doSave()方法基本上做到以下几点:我有一个sfWidgetFormPropelChoice字段,用户可以选择,或键入一个新的选项。我怎样才能改变小部件的价值?或者,也许我正在接近这个错误的方式。因此,这里是我如何推翻了DoSave就会()方法:在symfony中,如何设置表单域的值?

public function doSave($con = null) 
{ 
    // Save the manufacturer as either new or existing. 
    $manufacturer_obj = ManufacturerPeer::retrieveByName($this['manufacturer_id']->getValue()); 
    if (!empty($manufacturer_obj)) 
    { 
     $this->getObject()->setManufacturerId($manufacturer_obj->getId()); // NEED TO CHANGE THIS TO UPDATE WIDGET'S VALUE INSTEAD? 
    } 
    else 
    { 
     $new = new Manufacturer(); 
     $new->setName($this['manufacturer_id']->getValue()); 
     $new->save(); 
     $this->getObject()->setManufacturerId($new->getId()); // NEED TO CHANGE THIS TO UPDATE WIDGET'S VALUE INSTEAD? 
    } 

    parent::doSave($con); 
} 

回答

9

您应该使用setDefault或setDefaults,然后它会使用绑定值自动填充。

(sfForm) setDefault ($name, $default) 
(sfForm) setDefaults ($defaults) 

使用

$form->setDefault('WidgetName', 'Value'); 
$form->setDefaults(array(
    'WidgetName' => 'Value', 
)); 
2

你可以在动作做到这一点:

$this->form->getObject()->setFooId($this->foo->getId()) /*Or get the manufacturer id or name from request here */ 
$this->form->save(); 

但我喜欢做那种工作的您与您的制造商直接做在我的同行中,所以我的业务逻辑总是在同一个地方。

我在表单中放置的主要是验证逻辑。

public function save(PropelPDO $con= null) 
{ 
    if ($this->isNew() && !$this->getFooId()) 
    { 
    $foo= new Foo(); 
    $foo->setBar('bar'); 
    $this->setFoo($foo); 
    } 
} 
+0

感谢您的答复!你会如何去做同行中的这项工作?既然它与形式有关,不应该以形式出现吗?对等体没有可以是ID或新名称的表单数据。 – 2009-06-23 04:51:15

1

两个假设这里::1)你的形式得到制造商的名称和b)模型希望制造商

的ID

的放什么在同行的保存方法示例

public function doSave($con = null) 
{ 
    // retrieve the object from the DB or create it 
    $manufacturerName = $this->values['manufacturer_id']; 
    $manufacturer = ManufacturerPeer::retrieveByName($manufacturerName); 
    if(!$manufacturer instanceof Manufacturer) 
    { 
     $manufacturer = new Manufacturer(); 
     $manufacturer->setName($manufacturerName); 
     $manufacturer->save(); 
    } 

    // overwrite the field value and let the form do the real work 
    $this->values['manufacturer_id'] = $manufacturer->getId(); 

    parent::doSave($con); 
}