我有两个具有一对多关系的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对象的数组?
因为您的LicenseProductRelationType
是LicenseProductType
的嵌入形式,您必须在LicenseProductRelationType
上实现getDefaultOptions
方法并将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',
);
}
必须使用实体类型。这一个是学说启用,并给你很多爱/权力来处理实体集合。确保设置"multiple" => true