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', )); } }
source share