Symfony 2 Form Error "This form should not contain additional fields." when submitting the form

I submit the form and process it in the Sylius ResourceController , which submits the form and validates it.

This is the in situ form:

 <tr> <form method="post" action="{{ path('backend_course_row_update', { 'courseeId' : course.id, 'id' : row.id }) }}" novalidate> {{ form_widget(form.channel) }} {{ form_widget(form.name) }} {% for size in form.sizes %} {{ form_row(size) }} {% endfor %} {{ form_row(form._token) }} <td align="right" style="width: 140px;"> <button class="btn btn-primary" type="submit"> <i class="glyphicon glyphicon-save"></i>Save </button> </td> </form> </tr> 

The "form" here is CourseGuideRowType , which is as follows:

 /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('channel', 'channel_choice', array( 'required' => false )) ->add('name', 'text') ->add('sizes', 'course_guide_row_sizes', array('numColumns' => $options['numColumns'])) ; } 

CourseGuideRowSizesType as follows:

 /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { for ($i = 0; $i < $options['numColumns']; $i++) { $builder->add($i, 'text', array('required' => 'false')); } $builder->addEventListener( FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($options) { $form = $event->getForm(); for ($i = 0; $i < $options['numColumns']; $i++) { if (empty($form->get($i)->getData())) { $form->remove($i, 'text'); } } } ); } 

However, when I submit the form and upload errors like this:

$form->submit($request, !$request->isMethod('PATCH'))->getErrors()

I get:

 "This form should not contain extra fields." #messageParameters: array:1 [▼ "{{ extra_fields }}" => "0", "1", "2", "3", "4", "5" ] -extraData: array:6 [▼ 0 => "36" 1 => "38" 2 => "40" 3 => "42" 4 => "44" 5 => "46" ] 

"Additional data" is the "size" field.

Am I doing something obviously wrong here?

EDIT June 2017: now you can use 'allow_extra_fields' to suppress this error. http://symfony.com/doc/current/reference/forms/types/form.html#allow-extra-fields

+5
source share
1 answer

The error occurs because you define each size as form_row , for example.

 {% for size in form.sizes %} {{ form_row(size) }} // Extra field defined here {% endfor %} 

As pointed out in the comments, you should use CollectionType or create and use your own FormType in the same way.

This avoids the need to manually define additional fields in your form, and BTW remove the error.

EDIT

@nakashu recalled the workaround that will be used at the moment.

Just avoid the error by adding the following to your CourseGuideRowType :

 public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'allow_extra_fields' => true, )); } 

But this does not make you free from side effects during the processing / binding steps.

+8
source

Source: https://habr.com/ru/post/1243878/


All Articles