如何嵌入表单集合 - 一对多/多对一

时间:2015-06-23 20:58:46

标签: symfony symfony-forms

我有3个实体:

产品 - > (1:m)Product2Attribute - > (m:1)属性

每个产品都可以拥有更多属性。属性的值存储在关联实体Product2Attribute中。

我想在Product表单中生成属性字段。我有一个产品类型并嵌入了productAttributeAssociations的新集合,并创建了包含2个字段id和值的新表单类型Product2AttributeType。表单呈现:

{% for productAttribute in form.productAttributeAssociations %}
        {{ form_label(form.productAttribute.value) }}
        {{ form_widget(form.productAttribute.value) }}
{% endfor %}

产品形式:

public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder
        ->add('name', 'text')
        ->add('title', 'text')
        ->add('number', 'text')
        ->add('netPrice', 'text')
        ->add('grossPrice', 'text')
        ->add('description', 'textarea')
        ->add('category', 'entity', array(
            'class' => 'XXXBundle:Category',
            'query_builder' => function (EntityRepository $er) {
                return $er->createQueryBuilder('c')
                    ->orderBy('c.root', 'ASC')
                    ->addOrderBy('c.lft', 'ASC');
            },
            'property' => 'indentedTitle',
            'multiple' => true
        ))
        ->add('productAttributeAssociations', 'collection', array(
            'type' => new \XXXBundle\Form\Product2AttributeType()
        ))
        ->add('save', 'submit');
}

public function getName() {
    return 'xxx_product';
}

public function configureOptions(OptionsResolver $resolver) {
    $resolver->setDefaults(array(
        'data_class' => 'XXXBundle\Entity\Product',
        'csrf_protection' => true,
        'csrf_field_name' => '_token',
        'intention' => 'product_item',
    ));
}

和Product2AttributeType:

public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder->add('id', 'hidden');
    $builder->add('value', 'text');
}

public function configureOptions(OptionsResolver $resolver) {
    $resolver->setDefaults(array(
        'data_class' => 'XXXBundle\Entity\Product2Attribute',
    ));
}

public function getName() {
    return 'product2attribute';
}

当我按产品填充表单而没有任何属性时,表单将呈现为没有任何属性字段,但是当我使用具有至少一个属性的Product时,会发生错误:

 The forms view data is expected to be of type scalar, array or an instance     
    of \ArrayAccess, but is an instance of class 
    XXXBundle\Entity\Product2Attribute.   You can avoid this error by setting 
    the "data_class" option to "XXXBundle\Entity\Product2Attribute" or by adding 
    a view transformer that transforms an instance of class 
    XXXBundle\Entity\Product2Attribute to scalar, array or an instance of 
    \ArrayAccess.
    500 Internal Server Error - LogicException

我的问题是:

谢谢。

0 个答案:

没有答案