goldlife
goldlife

Reputation: 1989

Symfony validation get specific error by property

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\ConstraintViolationListInterfac‌​e - 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

Answers (2)

Jovan Perovic
Jovan Perovic

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 ConstraintViolationListInterfac‌e, 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 you

Form 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

Matteo
Matteo

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

Related Questions