Confirm dynamic selection field filling

I have two selection fields: one depends on the other.

When creating a form in a dependent field, an array with an empty choice is received.

Then I fill out this field in JavaScript, requesting some data from the action.

The problem comes from checking. Of course, this is not so, because single or multiple values ​​cannot be valid with respect to an empty value. To solve this, I created a PRE_BIND listener that basically deletes, then recreates the select box with the correct values, but it still fails the test.

$form->getErrors() returns nothing but $form->getErrorsAsString() returns me an error in the select box.

My form:

 <?php namespace Foo\BarBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class BarFormType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { // other fields // This field is filled in ajax $builder->add('stores', 'choice', array( 'label' => 'form.label.stores', 'translation_domain' => 'FooBarBundle', 'choices' => $options['storesList'], 'required' => false, 'multiple' => true, 'auto_initialize' => false, 'attr' => array( 'class' => 'chzn-select', 'placeholder' => 'form.placeholder.stores' ))); $func = function (FormEvent $e) use ($options) { $data = $e->getData(); $form = $e->getForm(); if ($form->has('stores')) { $form->remove('stores'); } $brand = isset($data['brand']) ? $data['brand'] : null; if ($brand !== null) { $choices = $options['miscRepo']->getStoresNameIndexedById($brand); $choices = array_keys($choices); $choices = array_map('strval', $choices); } else { $choices = array(); } $form->add('stores', 'choice', array('choices' => $choices, 'multiple' => true, 'attr' => array('class' => 'chzn-select'))); }; $builder->addEventListener(FormEvents::PRE_SUBMIT, $func); } public function getName() { return 'bar_form_campaign'; } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setRequired(array( 'storesList', 'miscRepo', )); } } 
+6
source share
1 answer

I had the same problem as yours: updating the field using javascript, but the validation failed. In the PRE_SUBMIT event, read the value you added using javascript, query and get an object with this identifier, and update the field selection.

 $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) { $data = $event->getData(); $form = $event->getForm(); $pageId = $data['page_id']; $page = $this->myManager->getPage($pageId); $options = array($page->getId() => $page->getTitle()); $form->add('page_id', 'choice', array( 'label' => 'Select page', 'choices' => $options, 'required' => true, 'placeholder' => 'Select page' )); $form->getData()->setPageId($pageId); }); 
0
source

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


All Articles