从嵌套表单中调用$ builder-> getData()始终返回NULL

时间:2014-02-18 18:18:39

标签: symfony symfony-forms symfony-2.3

我正在尝试以嵌套的形式存储数据,但在调用$builder->getData()时,我总是得到NULL。

有谁知道如何在嵌套表单中获取数据?

这是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';
    }
}

谢谢!

3 个答案:

答案 0 :(得分:7)

您需要使用FormEvents :: POST_SET_DATA来获取表单对象:

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

答案 1 :(得分:3)

这是一个(非常烦人的)已知问题:

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

因为它适用于简单形式但不适用于复合形式。从文档(参见http://symfony.com/doc/master/form/dynamic_form_modification.html),您必须:

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

答案 2 :(得分:-1)

表单是在绑定数据之前构建的(也就是说,绑定数据在调用AbstractType::buildForm()时不可用)

如果要根据绑定数据动态构建表单,则需要使用事件

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