18

I'm working on a symfony2 backend for a backbone.js application. I have my model and form.

However, backbone.js sends some additional properties to the REST API when it's creating/updating a model and I'm struggling to get the form to validate.

How can I get a form in symfony2 to accept additional data, or how can I drop particular keys before binding data to a form?

4 Answers 4

64

You should use option "allow_extra_fields".

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
        $resolver->setDefaults(
        array(
            'allow_extra_fields' => true
        )
    );
}

For symfony 2.8+ use configureOptions(OptionsResolver $resolver) instead of setDefaultOptions(OptionsResolverInterface $resolver)

Sign up to request clarification or add additional context in comments.

4 Comments

allow_extra_fields will not be included in symfony until 2.6. This will be the right way to add extra fields. mapped = false would be the suggested way if you know the extra field names that will be submitted.
As 2.6 has now been marked as a stable release this should be marked as the correct answer. @user1432227
@krun you could also add the symfony 2.8/3.* example where it is: configureOptions(OptionsResolver $resolver) instead of the setDefaultOptions function.
Does there any option where I can set 'llow_extra_fields' to rue for all my forms ? I mean some configuration inside my config file ..maybe ?
16

property_path is now deprecated in sf 2.1, use "mapped" instead

$builder
    ->add("firstName", "text")
    ->add("lastName", "text")
    ->add("tac", "checkbox", array(
        "mapped" => false
    )
);

Comments

12

To get Symfony2 accept additional data, add the additional fields to your form builder, and set their property_path option to false:

Example:

$builder
    ->add('my_additional_field', 'checkbox', array(
        'mapped' => false,
    ));

You don't need to drop the keys before binding the data, they'll be ignored anyway.

2 Comments

+1 Quick note for >= 2.1: "New in version 2.1: Since 2.1, the mapped option has been added for this use-case." symfony.com/doc/2.1/reference/forms/types/hidden.html#mapped
Maybe you should consider to update your answer adding for what version is valid.
2

You can listen for FormEvents::BIND_CLIENT_DATA (or FormEvents::PRE_BIND if you are using 2.1 dev) event listener and add/remove fields. See this cookbook entry.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.