FriendsOfSymfony / FOSUserBundle

Provides user management for your Symfony project. Compatible with Doctrine ORM & ODM, and custom storages.
https://symfony.com/doc/master/bundles/FOSUserBundle/index.html
MIT License
3.25k stars 1.57k forks source link

Validation and Error message in form #567

Open youuri opened 12 years ago

youuri commented 12 years ago

hi,

I'm working on registration form and i have some problems with errors messages after validation. I'm using a "form_theme" and all errors form registration form are displaying as a global error form and not as a field error.

{# Form Theme Row #############################################################} {% block field_row %} {% spaceless %}

{{ form_label(form) }} {{ form_widget(form) }} {{ form_errors(form) }}

{% endspaceless %} {% endblock field_row %}

{% block field_rows %} {% spaceless %}

{# Global Error #}
{{ form_errors(form) }}

{# Render Rows #}
{% for child in form %}
    {{ form_row(child) }}
{% endfor %}

{% endspaceless %} {% endblock field_rows %}

Is it possible to configure validator or an other way to put error as field-error and not global-error?

Best regards

olotintemitope commented 6 years ago

@youuri Simply add the below to your controller and pass it down to the view

private function getErrorMessages(Form $form) 
{
        $errors = [];

        foreach ($form->getErrors() as $key => $error) {
            if ($form->isRoot()) {
                $errors['#'][] = $error->getMessage();
            } else {
                $errors[] = $error->getMessage();
            }
        }

        foreach ($form->all() as $child) {
            if (!$child->isValid()) {
                $errors[$child->getName()] = $this->getErrorMessages($child);
            }
        }

        return $errors;
    }