I'm trying to populate $errors['field_name'] = 'Error message';
in my controller so that I can pass the variable to twig for further processing. How can I loop thru the errors and create my own array variable?
I've checked and applied these but didn't get the exact answer, or maybe I missed.
- Accessing and Debugging Symfony Form Errors
- Symfony2 : How to get form validation errors after binding the request to the form (Works but is it reliable?)
- Symfony2 – Getting All Errors From a Form in a Controller (Overkill)
FORM TYPE
->add('name', 'text', array('label' => 'Name', 'error_bubbling' => true))
->add('origin', 'text', array('label' => 'Origin', 'error_bubbling' => true))
TWIG
{% if errors is defined %}
<ul>
{% for field, message in errors %}
<li>{{ field ~ ':' ~ message }}</li>
{% endfor %}
</ul>
{% endif %}
CONTROLLER
public function submitAction(Request $request)
{
$form = $this->createForm(new BrandsType(), new Brands());
$form->handleRequest($request);
if ($form->isValid() !== true)
{
$errors['field_name'] = 'Error message';
return $this->render('CarBrandBundle:brands.html.twig',
array('errors' => $errors, 'form' => $form->createView()));
}
}
Try a method like this:
This method will return what you want, which is associative array with form errors.
The usage of it would be in your case (controller):
This usage assumes you have
getErrorMessages
method in your controller, however a better idea would be creating some class with this method and registering it as a service (you might want to reuse it in other controllers)