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

use*_*226 8 symfony-forms symfony 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
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

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';
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Tio*_*ois 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!
        });
Run Code Online (Sandbox Code Playgroud)


Tho*_*aux 6

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

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);
        }
    });
Run Code Online (Sandbox Code Playgroud)


Pet*_*ley -1

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

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

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