我正在覆盖我的doSave()方法,基本上执行以下操作:我有一个用户可以选择的sfWidgetFormPropelChoice字段,或者键入一个新选项。如何更改小部件的值?或许我接近这个错误的方式。所以这就是我如何覆盖doSave()方法:
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);
}
答案 0 :(得分:9)
你应该使用setDefault或setDefaults然后它将使用绑定值自动填充。
(sfForm) setDefault ($name, $default)
(sfForm) setDefaults ($defaults)
使用
$form->setDefault('WidgetName', 'Value');
$form->setDefaults(array(
'WidgetName' => 'Value',
));
答案 1 :(得分:2)
你可以在行动中做到:
$this->form->getObject()->setFooId($this->foo->getId()) /*Or get the manufacturer id or name from request here */
$this->form->save();
但我更喜欢直接在我的Peer中与制造商一起做的工作,所以我的业务逻辑总是在同一个地方。
我在表单中添加的内容主要是验证逻辑。
在Peer的保存方法中放入什么的示例:
public function save(PropelPDO $con= null)
{
if ($this->isNew() && !$this->getFooId())
{
$foo= new Foo();
$foo->setBar('bar');
$this->setFoo($foo);
}
}
答案 2 :(得分:1)
这里有两个假设:a)您的表单获取制造商的名称,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);
}