Search code examples
symfonyvalidationconstraintssymfony6

Valdiator for related entites


I have two entities, i want to have a custom validator constraint to ensure that both entities share one value.

Example:

Entity Region:

  • has field city
  • has multiple houses as OneToMany relation
  • constraint to allow only houses that have the same city

Entity House:

  • has field city
  • has one region as ManyToOne relation

your answer with any hints on how to achieve this is highly appreciated.


Solution

  • Here is a solution to achieve what you want to do:

    In your FormType, add an event listener on PRE_SUBMIT and add the constraint in like this:

    use Symfony\Component\Form\FormEvent;
    use Symfony\Component\Form\FormEvents;
    use Symfony\Component\Validator\Constraints\EqualTo;
    
    // ...
    
    $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
        $data = $event->getData();
        $form = $event->getForm();
    
        if (isset($data['cityA'])) {
            $form->add('cityB', TextType::class, [
                'constraints' => [
                    new EqualTo([
                        'value' => $data['cityA'],
                        'message' => 'Must be the same as cityA',
                    ]),
                ],
            ]);
        }
    
        // Here other constraints
    });