I have created a custom form type and contraint in Symfony.
The constraint is attached to the form type like this:
->add('customField', 'customField', array(
'required' =>
'mapped' => false,
'constraints' => array(new CustomField()),
))
where CustomField is the constraint class.
The constraint validator's validate() method looks like this:
public function validate($value, Constraint $constraint)
{
//I know this will always fail, but it's just for illustration purposes
$this->context->addViolation($constraint->message);
}
I have changed the form's default template like this:
{% block form_row -%}
<div class="form-group">
{{- form_widget(form) -}}
{{- form_errors(form) -}}
</div>
{%- endblock form_row %}
{% block customField_widget %}
{% spaceless %}
<!-- actually different but you get the idea -->
<input type="text" name="customField" id="customField" />
{% endspaceless %}
{% endblock %}
{% block form_errors -%}
{% if errors|length > 0 -%}
{%- for error in errors -%}
<small class="help-block">
{{ error.message }}
</small>
{%- endfor -%}
{%- endif %}
{%- endblock form_errors %}
And in the template where the form is displayed, I've added some code to display the errors attached to the whole form rather than individual field errors:
{{ form_start(formAdd) }}
{% if formAdd.vars.valid is same as(false) -%}
<div class="alert alert-danger">
<strong>Errors!</strong> Please correct the errors indicated below.
{% if formAdd.vars.errors %}
<ul>
{% for error in formAdd.vars.errors %}
<li>
{{ error.getMessage() }}
</li>
{% endfor %}
</ul>
{% endif %}
</div>
{%- endif %}
...
The problem with all this, the validator of this particular field, is attaching the constraint violation to the form object and not to the customField form type. This causes the error to be finally displayed with the form's general errors instead of being displayed as a field error.
Now, this is not the only custom form type and validator I added but it's the only one that displays this behavior, without me being able to identify the difference between this one and the rest. Can you spot what is wrong here?