Reputation: 1989
I know how to validate and how I can retrieve the error messages. But how can I get a specific error entry by property?
NOT like this:
{% for error in errors %}
<li>{{ error.message }}</li>
{% endfor %}
I mean something like this:
getError($errors, 'myProperty');
Is something like this possible?
I use the validator, but not the form class. I got \Symfony\Component\Validator\ConstraintViolationListInterface - with an array of all error messages.
I am sadly not in Twig context ... I need it for smarty .. I want to show directly a error message for a specific field like this:
<label for="city">{getError($errors, 'myProperty')}</label>
<div class="form-group">
<input class="form-control" name="city" id="city" placeholder="City *" type="text">
</div>
Upvotes: 3
Views: 1143
Reputation: 20193
Validator
-based idea:So, if you have access to your Validator
class, you might be able to do something like this:
$validator->atPath('myField')->getViolations();
which would return ConstraintViolationListInterface
, but due to atPath
call, it should return only a subset of violations.
Must say, I have never tried it myself, but it sure sounds like it could work.
Form
-based solution, not very useful to youForm
class has the method getErrors()
method:
public function getErrors($deep = false, $flatten = true)
In your example, you could call:
form.myField.getErrors()
Or via variable:
{% set varWithFormName = "myField" %}
form[varWithFormName].getErrors()
Hope this helps...
Upvotes: 1
Reputation: 39380
Try if this code works for you:
{% for error in errors %}
{% if error.propertyPath == 'myProperty' %}
<li>{{ error.message }}</li>
{% endif %}
{% endfor %}
You can create a TWIG macro that accept the errors and the field that handle the render.
Let me know
Upvotes: 1