关于类型的symfony的动态形式

时间:2017-03-30 14:13:39

标签: php forms symfony

我正在尝试在两个choiceList上做一个动态表单,我试图按照有关SYmfony的文档:http://symfony.com/doc/current/form/dynamic_form_modification.html#dynamic-generation-for-submitted-forms但是正在使用两个实体,我必须使用choiceList任何人都可以帮助我关于这是我的UserTYpe:

$

builder
    ->add('at', ChoiceType::class, array(
        'label' => ' ',
        'choices' =>array(
            "42consulting.fr" => "42consulting.fr",
            "42consulting.lu" => "42consulting.lu",
            "42mediatvcom.fr" => "42mediatvcom.fr",
            "42consulting.ma" => "42consulting.ma",
            "42consulting.nl" => "42consulting.nl",
        ),
        'attr' => array(
            'class' => 'form-control',
            'placeholder' => 'service',
        ),
    )
);

$formModifier = function (FormInterface $form, User $at= null) {
    $services = null === $at ? array() :$at->getService();

    $form->add('service', ChoiceType::class, array(
                'label' => 'Service',
                'choices' => array(
                    "42Consulting Paris" => "Saint-Mandé",
                    "42Consulting Lux" => "Luxembourg",
                    "42MediaTelecom" => "Issy-Les-Moulineaux",
                    "42Consulting Maroc" => "Casablanca"
                ),
                'attr' => array(
                    'class' => 'form-control service',
                    'placeholder' => 'service',
                ),
            )
    );

};

$builder->addEventListener(
    FormEvents::PRE_SET_DATA,
    function (FormEvent $event) use ($formModifier) {
        $data = $event->getData();

        $formModifier($event->getForm(), $data->getAt());
    }
);

$builder->get('at')->addEventListener(
    FormEvents::POST_SUBMIT,
    function (FormEvent $event) use ($formModifier) {
        $at = $event->getForm()->getData();

        $formModifier($event->getForm()->getParent(), $at);
    }
);

和我得到的错误是:类型错误:传递给BackBundle \ Form \ UserType :: BackBundle \ Form {closure}()的参数2必须是BackBundle \ Entity \ User的实例,给出字符串,在第263行的/home/work/Sites/backoffice-ad/src/BackBundle/Form/UserType.php中调用(在此行:$ formModifier($ event-> getForm() - > getParent(),$在);)

1 个答案:

答案 0 :(得分:0)

在线

$formModifier = function (FormInterface $form, User $at= null) {

您的$ at,如声明,此参数必须是User实体的实例。但是当你调用这个函数时,你传递了一个字符串:

$builder->addEventListener(
    FormEvents::PRE_SET_DATA,
    function (FormEvent $event) use ($formModifier) {
        $data = $event->getData();
        $formModifier($event->getForm(), $data->getAt());
    }
);

你试过了吗?

$formModifier($event->getForm(), $data);

我不确定,但我认为这是调用getAt()时出现的问题,此方法返回字符串。 $data变量可能是用户实体的一个实例。