-->

Calling $builder->getData() from within a nested f

2019-03-19 14:36发布

问题:

I'm trying to get data stored in a nested form but when calling $builder->getData() I'm always getting NULL.

Does anyone knows what how one should get the data inside a nested form?

Here's the ParentFormType.php:

class ParentFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('files', 'collection', array(
            'type'          => new FileType(),
            'allow_add'     => true,
            'allow_delete'  => true,
            'prototype'     => true,
            'by_reference'  => false
        );
    }
}

FileType.php

class FileType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // Each one of bellow calls returns NULL
        print_r($builder->getData());
        print_r($builder->getForm()->getData());
        die();

        $builder->add('file', 'file', array(
            'required'    => false,
            'file_path'   => 'file',
            'label'       => 'Select a file to be uploaded',
            'constraints' => array(
                new File(array(
                    'maxSize' => '1024k',        
                ))
            ))
        );
    }

    public function setDefaultOptions( \Symfony\Component\OptionsResolver\OptionsResolverInterface $resolver )
    {
        return $resolver->setDefaults( array() );
    }

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

Thanks!

回答1:

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!
        });


回答2:

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);
        }
    });


回答3:

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