Symfony2. How to allow form to ignore extra fields

2019-02-14 22:55发布

问题:

This question already has an answer here:

  • Symfony2.4 form 'This form should not contain extra fields' error 4 answers

I need to post some data to my Symfony form and I use submit() method for this.

But when request contains some extra data, I got error:

"This form should not contain extra fields"

Is it possible to let form miss the extra data using form configuration ?

Maybe another way for doing this exists?

Notice: I need submit() method, not handleRequest() because I post my data through cross-domain ajax request, so form cannot be submitted this way. Reason: isValid() return false, because isSubmitted() return false.

P.S. Of course, I can create service that will be handle my request before passing it to the form, but maybe more elegant way exists.

回答1:

In your Form Type:

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\YourEntity',
            'translation_domain' => strtolower('entity_translation_domain'),
            'allow_extra_fields' => true,
        ));
    }

The allow_extra_fields will enable your form to receive the extra data