tetranz
tetranz

Reputation: 1972

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?

Upvotes: 25

Views: 22560

Answers (3)

Peyman Mohamadpour
Peyman Mohamadpour

Reputation: 17964

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

Upvotes: 4

fkoessler
fkoessler

Reputation: 7276

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 )

Upvotes: 68

Elnur Abdurrakhimov
Elnur Abdurrakhimov

Reputation: 44851

Since Symfony 2.1, use the mapped option:

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

Upvotes: 30

Related Questions