1

I'm passing $errors to Twig, generated from this:

$insert = new MyEntity();
$insert->setTest1( 'testtesttest' );
$validator = $this->get('validator');
$errors = $validator->validate($insert);

...how do I get a specific error value, something like this if it worked?

{{ errors('field1') }}

...which should just return the error message, e.g. "That is not a valid email address" etc.

I know I can loop through to get all of them:

{% for err in errors %}
    {{ err.label }}: {{ err.value }}<br />
{% endfor %}

...but I just want one specific one

2
  • didn't you already ask how to convert the errors to an array? what exactly do you want to achieve with your validation? what are you validating? wouldn't maybe a form suit here? ... a list of all errors , fields and messages separated by : and followed by a <br/> ? ... or will there another question be following :) Commented Jul 8, 2013 at 0:20
  • You asked me to post this question as you said it was different to the other one. stackoverflow.com/questions/17516070/… I just need to get one specific value from the Validation errors object when passed to Twig. Commented Jul 8, 2013 at 0:25

1 Answer 1

1

You cant just access the fieldname of an array of validation-error objects directly. You have to search it by looping.

{% for error in errors %}
   {% if error.propertyPath = 'fieldname' %}
      {{ error.propertyPath }}: {{ error.message }}
   {% endif %}
{% endfor %}

But maybe you're better off just using ...

$errors = $validator->validateProperty($insert, 'fieldname);

... in your controller and just passing the list of errors for the one property into your template.

Sign up to request clarification or add additional context in comments.

3 Comments

Oh, ok, thanks. I thought about doing that but I'm trying to use as many best practices as possible. I hoped for a simple {{ errors(field name) }} thing. Thanks again
that's possible using forms {{ form_errors(form.fieldName) }} , maybe you should look into the getErrorsAsString form method and/or dig deeper how it's done in the form component.
Thanks. I'm learning Symfony2 and haven't got to forms yet. It's one of the next topics though. None of what I'm doing is for production, it's all self-learning, so I thought I would thoroughly do a topic at a time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.