How do I add an unbound field to a form in Symfony which is otherwise bound to an entity?

梦想的初衷 提交于 2019-11-30 06:10:46
fkoessler

In your form add a text field with a false property_path:

$builder->add('extra', 'text', array('property_path' => false));

You can then access the data in your controller:

$extra = $form->get('extra')->getData();

UPDATE

The new way since Symfony 2.1 is to use the mapped option and set that to false.

->add('extra', null, array('mapped' => false))

Credits for the update info to Henrik Bjørnskov ( comment below )

Since Symfony 2.1, use the mapped option:

$builder->add('extra', 'text', [
    'mapped' => false,
]);

According to the Documentation:

allow_extra_fields

Usually, if you submit extra fields that aren't configured in your form, you'll get a "This form should not contain extra fields." validation error.

You can silence this validation error by enabling the allow_extra_fields option on the form.

mapped

If you wish the field to be ignored when reading or writing to the object, you can set the mapped option to false.

class YourOwnFormType extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            array(
                'allow_extra_fields' => true
            )
        );
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $form = $builder
            ->add('extra', TextType::class, array(
                'label' => 'Extra field'
                'mapped' => false
            ))
        ;
        return $form;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!