I have two entities, i want to have a custom validator constraint to ensure that both entities share one value.
Example:
Entity Region:
Entity House:
your answer with any hints on how to achieve this is highly appreciated.
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
});