Question

I am trying to show error message related to a specific form_field in twig, but it does not show anything.

I have defined error related to my formType field in validation.yml as

-\-\Entity\Customer:
    properties:
        address2:
            - NotBlank:
                message: 'Testing required'

and when I print:

//Controller Class
$validator = $this->get('validator');
$errors = $validator->validate($customer);

//Controller
return $this->render( 'MyBundle:RegistrationPages:register.html.twig', 
    array (
        'errors' => $errors,
        'form'=>$form
    )
);

It shows error message in:

//Twig
{% if errors is defined %} 
    <h1>The Form has following errors</h1> 
    {% for error in errors %} 
        {{ error.message }} 
    {% endfor %} 
{% endif %}

outputs:

Testing Required

but:

{{ form_errors(form.address2) }}

is not showing anything.

Was it helpful?

Solution

As you can see in your validation file, the NotBlank constraint is defined on your address2 property:

properties:
    address2:
        - NotBlank:
             message: 'Testing required'

All errors on that form field will therefore be available on that field:

{{ form_errors(form.address2) }}

Note: You don't have to pass the errors like this to your template:

//Get all errors that are attributed to the entity itself
{{ form_errors(form) }}
//Get all errors for the individual field `address2 `
{{ form_errors(form.address2) }}

OTHER TIPS

In short : if you just validate the object, but not the form, you won't have errors in your form.

If you do $errors = $validator->validate($customer); you validate the $customer not the form. So the errors are not attached to the form, they are just returned and you have to send them to the template the way you do in your question.

If you want to validate the form and to be able to access the errors in the form object, use $form->isValid(); (I cannot show you more because I don't have your form code.)

http://symfony.com/doc/current/book/validation.html#validation-and-forms

you must render the view after $form->handleRequest($request) . That means you should write your code like this:

$form->handleRequest($request);
$form_view = $form->createView();

.... ....

return $this->render( 'MyBundle:RegistrationPages:register.html.twig', 
    array (
        'errors' => $errors,
        'form'=>$form_view
    )
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top