在表单配置中调用getObject()时,Symfony表单变得混乱

时间:2011-06-30 09:20:11

标签: forms configuration symfony1

我有一个与样本模型有 belongsTo 关系的应变模型,i。即菌株属于样品。

我正在以这种方式在StrainForm configure()方法中配置隐藏字段:

$defaultId = (int)$this->getObject()->getSample()->getTable()->getDefaultSampleId();
$this->setWidget('sample_id', new sfWidgetFormInputHidden(array('default' => $defaultId)));

每当我创建一个新的Strain时,$form->save()都会失败。调试工具栏显示它首先尝试保存Sample对象,但我不知道原因。

但是,如果我使用表格检索默认样本ID,它就像魅力一样:

$defaultId = (int)Doctrine_Core::getTable('Sample')->getDefaultSampleId();
$this->setWidget('sample_id', new sfWidgetFormInputHidden(array('default' => $defaultId)));

我的问题是getObject()->getSample()...方法序列会导致StrainForm认为必须保存Sample对象而不是Strain

我尝试使用xdebug进行调试,但我无法得出一个明确的结论。

有什么想法吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

当您致电getSample时,会创建一个Sample实例。它会自动附加到Strain对象,因此当您保存时也可以保存Sample。

调用getSample的一种有效方法是将Strain对象链接到Sample表,因为我假设你只是这样做,所以不要以相关的形式硬编码Sample的名字:

// note Sample is the alias not necessarily the Model name
$defaultId = Doctrine_Core::getTable($this->getObject()->getTable()->getRelation('Sample')->getModel())->getDefaultId(); 

答案 1 :(得分:0)

您的解决方案可能会失败,因为您无法在新表单上使用getObject()(因为在该阶段该对象根本不存在)。

编辑:为什么不通过options数组传递默认Sample,然后通过$ this-> getOption('Sample')从表单类中访问它(如果我没记错的话)?