Sometimes we have a "HiddenType" field in a Symfony 3 form and this field is completed with a step outside the form (example: a service that allows you to choose a reseller on a Google map).
We would like to have a validation on this field and we also use the jquery-validate library. Here's how to proceed.
To begin, you must add the validator on the field in the buildForm() method in your class. We want it to be mandatory:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add(...)
...
->add('dealer_code', HiddenType::class, array(
'required' => true,
));
}
In your Twig view, it will be necessary to display the validation message where you want it to appear:
<div class="input-field col-md-12">
<span>Select a dealer</span>
{{ form_widget(form.selectionner) }} {# a button that leads us to our reseller location service #}
{{ form_errors(form.dealer_code) }} {# we decide to display the error message here otherwise this message will be displayed below all fields of the form #}
{{ form_widget(form.dealer_code) }}
</div>
At the level of jquery-validate it will be necessary to add the option "ignore" with an empty array otherwise the validator on the fields of type "hidden" will be ignored:
$("#formValidate").validate({
ignore: [],
...,
messages: {
dealer_code: {
required: "Please choose a reseller"
}
},
});