Reputation: 2154
Consider the following form:
$builder->add('home_team', 'choice', [$options])
->add('away_team', 'choice', [$more_options])
->add('timestamp', 'datetime_picker', [$usual_stuff]);
I wish to validate these fields, and see that no other Match
exists with the same home_team
, away_team
and timestamp
.
I have made a UniqueMatchValidator
with a validate()
function but I need some help here.
I'm going to do a database call with the values from the form to check for duplicates, but in order to do that, I need to know the values of all three fields, while applying the Validator to only one of the fields.
Question
How can I access the values of all the form fields from inside the Validator?
Upvotes: 1
Views: 372
Reputation: 316
As mentioned above it's better to use FormTypes and data classes.
However even with arrays you can use form validation and get all fields using event listener:
$builder
->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
$event->getData(); //you will get array with field values
$event->getForm()->addError(...); // if something happens error can be addded
})
Actually form validator uses this event too.
Upvotes: 1
Reputation: 215
Your form should basically contains an entity. You need to do your validations using callbacks in the entity. Using callback, you can access all the properties of that entity.
This link will surely help you to understand it better: Symfony2 Form Validation Callback
Upvotes: 0