简体   繁体   English

如何在Symfony2中正确设置表单收集的“ data_class”?

[英]How to properly set 'data_class' for form collection in Symfony2?

I would like to have a collection of forms. 我想收集一些表格。 My brick form is defined like: 我的积木形式定义如下:

class ImportPaymentsType extends AbstractType
{
    public function getName()
    {
        return 'import_payments_type';
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('caisse', 'entity', array(
            'label' => null,
            'class' => 'ACME\AppBundle\Entity\Caisse',
            'property' => 'name',
            'empty_value' => 'Choose an option',
        ))
        ->add('label', 'text', array(
            'label' => null,
        ))
        ->add('credit', 'number', array(
            'label' => null,
        ));
    }
}

In controller I construct this form like: 在控制器中,我构造如下形式:

    $data = array(
        'imports' =>
            array(
                'caisse' => $em->getRepository('ACMEAppBundle:Caisse')->findOneByCode('P6015C'),
                'label' => null,
                'credit' => null,
            )
    );

    $importForm = $this->createFormBuilder($data)
        ->add('imports', 'collection', array(
            'type' => new ImportPaymentsType(),
        ))->getForm();

The error I get is: 我得到的错误是:

The form's view data is expected to be of type scalar, array or an instance of \\ArrayAccess, but is an instance of class ACME\\AppBundle\\Entity\\Caisse. 表单的视图数据应为标量类型,数组类型或\\ ArrayAccess实例,但为ACME \\ AppBundle \\ Entity \\ Caisse类的实例。 You can avoid this error by setting the "data_class" option to "ACME\\AppBundleBundle\\Entity\\Caisse" or by adding a view transformer that transforms an instance of class ACME\\AppBundleBundle\\Entity\\Caisse to scalar, array or an instance of \\ArrayAccess. 您可以通过将“ data_class”选项设置为“ ACME \\ AppBundleBundle \\ Entity \\ Caisse”或添加将View类ACME \\ AppBundleBundle \\ Entity \\ Caisse转换为标量,数组或\\的实例的视图转换器来避免此错误。 ArrayAccess。

I tried to change ImportPaymentsType but it didn't work: 我试图更改ImportPaymentsType,但没有成功:

    ->add('caisse', 'entity', array(
        'label' => null,
        'class' => 'ACME\AppBundle\Entity\Caisse',
        'property' => 'description',
        'empty_value' => 'Choose an option',

        'data_class' => 'ACME\AppBundle\Entity\Caisse'

    ))

What should I do? 我该怎么办? Please help. 请帮忙。

'imports' should be an array of array. 'imports'应该是一个数组数组。

Try with: 尝试:

$data = array(
    'imports' =>
        array(
            array(
                'caisse' => $em->getRepository('ACMEAppBundle:Caisse')->findOneByCode('P6015C'),
                'label' => null,
                'credit' => null,
            )
        )
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM