0

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.

jmiguel
  • 296
  • 2
  • 5
  • 15

1 Answers1

1

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

Marino Di Clemente
  • 3,120
  • 1
  • 23
  • 24
  • I ended up validating it in the controller, regarding your answer I didn't actually try it but I have a doubt about it: does it throw the error _when both arrays are equal element-by-element_ or _when at least one element is in both arrays_? because I need the latter – jmiguel Apr 23 '14 at 16:25
  • well, looks like you changed the answer as I was writing, in the end I used the array_intersect function too, only in the controller, since I have never worked with the listeners, newbie me, and so far it's worked but just to be sure, would it be a problem to intersect the entities instead of the ids?, could it go wrong for some reason in the future? – jmiguel Apr 23 '14 at 16:31
  • probably directly intersecting the entity works equally, but i'm not sure, i trust more with ids:) – Marino Di Clemente Apr 23 '14 at 17:59