Handle form errors in controller and pass it to tw

2019-09-16 18:52发布

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.

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()));
    }
}

标签: php symfony twig
1条回答
欢心
2楼-- · 2019-09-16 19:43

Try a method like this:

public function getErrorMessages(FormInterface $form)
{
    $errors = array();

    //this part get global form errors (like csrf token error)
    foreach ($form->getErrors() as $error) {
        $errors[] = $error->getMessage();
    }

    //this part get errors for form fields
    /** @var Form $child */
    foreach ($form->all() as $child) {
        if (!$child->isValid()) {
            $options = $child->getConfig()->getOptions();
            //there can be more than one field error, that's why implode is here
            $errors[$options['label'] ? $options['label'] : ucwords($child->getName())] = implode('; ', $this->getErrorMessages($child));
        }
    }

    return $errors;
}

This method will return what you want, which is associative array with form errors.

The usage of it would be in your case (controller):

if ($form->isValid() !== true)
{
    $errors = $this->getErrorMessages($form);

    return $this->render('CarBrandBundle:brands.html.twig',
            array('errors' => $errors, 'form' => $form->createView()));
}

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)

查看更多
登录 后发表回答