Symfony2——来自表单集合元素的数据以数组而不是实体的形式结束


Symfony2 - data from a form collection element ends up as arrays instead of Entities

我有两个具有一对多关系的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对象的数组?

因为您的LicenseProductRelationTypeLicenseProductType的嵌入形式,您必须在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