Calling $builder->getData() from within a nested form always returns NULL

邮差的信 提交于 2019-12-03 06:48:00

You need to use the FormEvents::POST_SET_DATA to get the form object :

        $builder->addEventListener(FormEvents::POST_SET_DATA, function ($event) {
            $builder = $event->getForm(); // The FormBuilder
            $entity = $event->getData(); // The Form Object
            // Do whatever you want here!
        });

It's a (very annoying..) known issue:

https://github.com/symfony/symfony/issues/5694

Since it works fine for simple form but not for compound form. From documentation (see http://symfony.com/doc/master/form/dynamic_form_modification.html), you must do:

$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
        $product = $event->getData();
        $form = $event->getForm();

        // check if the Product object is "new"
        // If no data is passed to the form, the data is "null".
        // This should be considered a new "Product"
        if (!$product || null === $product->getId()) {
            $form->add('name', TextType::class);
        }
    });

The form is built before data is bound (that is, the bound data is not available at the time that AbstractType::buildForm() is called)

If you want to dynamically build your form based on the bound data, you'll need to use events

http://symfony.com/doc/2.3/cookbook/form/dynamic_form_modification.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!