phpsymfonyvalidationmultiple-choice

non overlaping choice lists in symfony2


Using Symfony 2.2.4.

I have a form with two choice lists(multiple,non expanded) showing the same elements(entities of a class). I need to throw an error(onsubmit) when the user selects the same element from both choice lists. Is there a way to validate this selection that does not need to traverse both lists checking each element, you know, like an automatic/built in validation.

I need to catch the error and bind it to one of the choice lists in a way that allows me to show it as any other error, meaning through form_errors(form).

Any tips appreciated.


Solution

  • the easiest way is to add a listener in the buildForm of the AbstractType class, here an example

        $builder->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $event) {
                $form = $event->getForm();
                $coll1 = $form['field1']->getData();
                $coll2 = $form['field2']->getData();
                $ids1 = $coll1->map(function($entity) { return $entity->getId(); })->toArray();
                $ids2 = $coll1->map(function($entity) { return $entity->getId(); })->toArray();
                $intersect = array_intersect($ids1, $ids2);
                if (!empty($intersect)) {
                    $form['field1']->addError(
                        new FormError('here the error')
                    );
                }
            }
        );
    

    Note that I have not tested the intersection of the collections but I hope the meaning is clear

    Another (a bit hardest) way is to create a custom validation constraint

    here the cookbook from symfony docs