Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Maybe I'm missing the obvious but how do I (or can I) add an extra "unbound" field to a Symfony form that is otherwise bound to an entity?

Let's say I have an entity with fields first_name and last_name. I do the typical thing in my form class buildForm method.

$builder
    ->add('first_name')
    ->add('last_name')
;

and this in my controller:

$editForm = $this->createForm(new MyType(), $entity);

That works nicely but I'd like to add another text box, let's call it "extra", and receive the value in the POST action. If I do $builder->add('extra')‍, it complains that

NoSuchPropertyException in PropertyAccessor.php line 479:

Neither the property "extra" nor one of the methods "getExtra()", "extra()", "isExtra()", "hasExtra()", "__get()" exist and have public access in class...

Which is correct. I just want to use it to collect some extra info from the user and do something with it other than storing it with the entity.

I know how to make a completely standalone form but not one that's "mixed". Is this possible?

like image 269
tetranz Avatar asked Oct 07 '12 01:10

tetranz


3 Answers

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 )

like image 66
fkoessler Avatar answered Oct 14 '22 05:10

fkoessler


Since Symfony 2.1, use the mapped option:

$builder->add('extra', 'text', [
    'mapped' => false,
]);
like image 39
Elnur Abdurrakhimov Avatar answered Oct 14 '22 03:10

Elnur Abdurrakhimov


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;
    }
}
like image 29
Pmpr.ir Avatar answered Oct 14 '22 03:10

Pmpr.ir