开发者

Get global form errors from the FormView in twig template

开发者 https://www.devze.com 2023-03-26 18:46 出处:网络
For rendering form errors in a twig template, you just have to use the form_errors twig macro without difference if it is a global form error or a field error.

For rendering form errors in a twig template, you just have to use the form_errors twig macro without difference if it is a global form error or a field error.

But in my case, a global error is not rendered like a field error, so I can't use the form_errors twig macro for the two cases. I decide to use the ma开发者_开发技巧cro for the field error & I would like to get the global form errors from the Symfony\Component\Form\FormView object. The goal is to iterate the global errors in the twig template & render them like I want.

Actually, I don't find any ressources on the symfony2 documentation which can help me.


Finally, I found the solution by myself. For the people who want to do the same thing, the solution is to call $formView->get("errors") which gives you an array of FormError


I'm using symfony 2.5 and it worked perfect for me in this way.

MyController

$error = new FormError(ErrorMessages::USER_NOT_AUTHENTICATED);
$form->addError($error);

MyView

{% for error in form.vars.errors %}
  <div class="alert alert-danger" role="alert">
    {{ error.messageTemplate|trans(error.messageParameters, 'validators')~'' }}
  </div>
{% endfor %}

hope this will save someones time.


in symfony 2.3 all accessor methods have been removed in favor of public properties to increase performance.

$formView->get("errors");

is now:

$formView->vars["errors"];

Visit UPGRADE-2.1.md and refer to section "Deprecations" for more information.

0

精彩评论

暂无评论...
验证码 换一张
取 消