【问题标题】:Symfony2 - data from a form collection element ends up as arrays instead of EntitiesSymfony2 - 来自表单集合元素的数据最终作为数组而不是实体
【发布时间】:2011-10-10 21:18:50
【问题描述】:

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

【问题讨论】:

    标签: php forms symfony


    【解决方案1】:

    因为您的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',
        );
    }
    

    【讨论】:

      【解决方案2】:

      您必须使用entity 类型。这个是启用 Doctrine 的,它给了你很多爱/权力来处理实体的集合。确保设置"multiple" => true

      【讨论】:

      • Ben,我将如何使用实体表单字段类型创建 新实体(LicenseProductRelation 类型),这是我在这种情况下想要做的?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      • 2015-05-11
      • 1970-01-01
      相关资源
      最近更新 更多