我有两个具有一对多关系的Doctrine实体,如下所示:
许可证
class License {
/**
* Products this license contains
*
* @var \Doctrine\Common\Collections\ArrayCollection
* @ORM\OneToMany(targetEntity="LicenseProductRelation", mappedBy="license")
*/
private $productRelations;
}
LicenseProductRelation:
class LicenseProductRelation {
/**
* The License referenced by this relation
*
* @var \ISE\LicenseManagerBundle\Entity\License
* @ORM\Id
* @ORM\ManyToOne(targetEntity="License", inversedBy="productRelations")
* @ORM\JoinColumn(name="license_id", referencedColumnName="id", nullable=false)
*/
private $license;
}
我有许可证实体的此表格:
class LicenseType extends AbstractType {
public function buildForm(FormBuilder $builder, array $options)
{
parent::buildForm($builder, $options);
$builder->add('productRelations', 'collection',
array('type' => new LicenseProductRelationType(),
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'label' => 'Produkte'));
}
}
这是LicenseProductRelation实体的表单:
class LicenseProductRelationType extends AbstractType {
public function buildForm(FormBuilder $builder, array $options) {
parent::buildForm($builder, $options);
$builder->add('license', 'hidden');
}
}
表单和实体当然包含其他字段,不会复制到此处以使帖子相对较短。
现在当我提交表单并将请求绑定到我的控制器中的表单时,我希望调用$license->getProductRelations()
返回一个LicenseProductRelation对象数组($license
是传入表单的实体因此,当我调用$form->bindRequest()
时,请求值被写入的对象。相反,它返回一个数组数组,内部数组包含表单字段名称和值。
这是正常行为还是我做了一个错误,以某种方式阻止表单组件理解License#productRelations
是一个LicenseProductRelation对象数组?
答案 0 :(得分:5)
由于您的LicenseProductRelationType
是LicenseProductType
的嵌入表单,因此您必须在getDefaultOptions
上实施LicenseProductRelationType
方法,并将data_class
设置为LicenseProductRelation
(包括其命名空间)。
请参阅文档:http://symfony.com/doc/current/book/forms.html#creating-form-classes
并向下滚动到标题为“设置data_class”的部分 - 它指出了您需要设置getDefaultOptions方法的嵌入表单。
希望这有帮助。
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Acme\TaskBundle\Entity\Task',
);
}
答案 1 :(得分:1)
您必须使用entity类型。这个是启用了Doctrine并且给予您很多爱/力量来处理实体集合。请务必设置"multiple" => true
。