Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 772
peris Avatar asked Feb 18 '14 18:02

peris


2 Answers

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!
        });
like image 56
Tiois Avatar answered Oct 02 '22 10:10

Tiois


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);
        }
    });
like image 20
Thomas Decaux Avatar answered Oct 02 '22 10:10

Thomas Decaux