Symfony2 - 来自表单集合元素的数据最终为数组而不是实体

Tob*_*ies 2 php forms symfony

我有两个具有一对多关系的Doctrine实体,如下所示:

执照

class License {    
    /**
     * Products this license contains
     * 
     * @var \Doctrine\Common\Collections\ArrayCollection
     * @ORM\OneToMany(targetEntity="LicenseProductRelation", mappedBy="license")
     */
    private $productRelations;
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

我有许可证实体的此表格:

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'));
    }
}
Run Code Online (Sandbox Code Playgroud)

这个表格适用于LicenseProductRelation实体:

class LicenseProductRelationType extends AbstractType {
    public function buildForm(FormBuilder $builder, array $options) {
        parent::buildForm($builder, $options);
        $builder->add('license', 'hidden');
    }
}
Run Code Online (Sandbox Code Playgroud)

表格和实体当然包含其他字段,这里不复制以保持帖子相对较短.

现在当我提交表单并将请求绑定到我的控制器中的表单时,我希望调用$license->getProductRelations()返回一个LicenseProductRelation对象数组($license是传入表单的实体,因此当我调用时,请求值被写入的对象$form->bindRequest()).相反,它返回一个数组数组,内部数组包含表单字段名称和值.

这是正常的行为还是我做了一个错误,以某种方式阻止表单组件理解License#productRelationsshound是一个LicenseProductRelation对象的数组?

Kas*_*een 5

因为您LicenseProductRelationType是一个嵌入式表单,LicenseProductType您必须实现该getDefaultOptions方法LicenseProductRelationType并设置data_classLicenseProductRelation(包括其命名空间).

请参阅文档: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',
    );
}
Run Code Online (Sandbox Code Playgroud)