首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >动态表单修改

动态表单修改
EN

Stack Overflow用户
提问于 2021-09-15 13:26:13
回答 1查看 45关注 0票数 0

我正在尝试创建一个包含两个动态表单元素的动态表单。

我遵循了https://symfony.com/doc/current/form/dynamic_form_modification.html#dynamic-generation-for-submitted-forms中的示例

我可以创建一个表单,显示新的表单元素的位置后,选择和提交体育。

然而,假设在选择位置并提交后,他们必须选择颜色,您将如何做到这一点?

我尝试为position添加一个新的事件侦听器,但它从未被调用过。

代码语言:javascript
复制
         $builder->get('position')->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $event) use ($formModifier) {
                // It's important here to fetch $event->getForm()->getData(), as
                // $event->getData() will get you the client data (that is, the ID)
                $position = $event->getForm()->getData();
                dump($position);

                $event->getForm()->add('colour', EntityType::class, [
                    'class' => Colour::class,
                    'placeholder' => '',
                    'choices' => ['red','green','blue'],
                ]);

            }
        );

例如,在这个测试数据中,运动是足球,位置是前锋,允许的颜色是红色和绿色,对于位置守门员,颜色可能是黄色和黑色。

EN

回答 1

Stack Overflow用户

发布于 2021-09-16 10:07:22

您正在尝试将colour字段添加到错误的表单。

使用$event->getForm(),您检索的是“位置”表单,而不是您想要修改的主表单。

为了更好地解释这一点,我对您的代码进行了注释。

代码语言:javascript
复制
/* Here you're correctly registering an event listener to the "position" field, POST_SUBMIT event */
$builder->get('position')->addEventListener(
    FormEvents::POST_SUBMIT,
    function (FormEvent $event) use ($formModifier) {
        // $event->getForm() here will return the "position" field form
        $position = $event->getForm()->getData();
        dump($position);

        // In the documentation example here the $formModifier closure is used
        // with $event->getForm()->getParent() as first argument

        // What you missed here is the getParent() call
        $event->getForm()
            ->getParent() // <- This will return the main form, the one you built with $builder
            ->add('colour', EntityType::class, [
                'class' => Colour::class,
                'placeholder' => '',
                'choices' => ['red','green','blue'],
            ]);
    }
);

您在事件侦听器中遗漏的是在add调用之前的getParent()调用。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69194079

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档