Skip to content

[Form] getErrorsAsArray for Form class #7977

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed

Conversation

TomiS
Copy link

@TomiS TomiS commented May 8, 2013

With this new handy method Form class is now able to provide all validation errors of a form (and its child forms) in a beautiful associative array tree that can, for example, easily be serialized to JSON for API responses and such. It seems quite a few people (including me) have had problems with the lack of this feature. At least this is the impression I had while browsing through questions in stackoverflow etc.

Implementation is similar to existing helper method getErrorsAsString so this one should behave however it behaves.

Q A
Bug fix? no
New feature? yes
BC breaks? no
Deprecations? no
Tests pass? yes (...I think. There were errors/fails but not caused by my code)
Fixed tickets
License MIT
Doc PR

So... Any future for this?

@TomiS
Copy link
Author

TomiS commented May 8, 2013

Here's an example of output (serialized in JSON for better readability)

{
    "title": [
        "Field cannot be empty."
    ],
    "category": [
        "Value must be 0 or more."
    ],
    "addresses": [
        {
            "street": [
                "Field cannot be empty."
            ]
        }
    ]
}

@raziel057
Copy link
Contributor

I already created a PR for this feature but there is place for improvements. See #7512

@TomiS
Copy link
Author

TomiS commented May 8, 2013

@raziel057 Oh... I guess I should have searched existing PRs a bit more intensively before coding :) Anyway, just adding weight for importance of this then.

@TomiS TomiS closed this May 8, 2013
@TomiS
Copy link
Author

TomiS commented May 8, 2013

Btw. Here's a similar workaround implementation for those who need it right now:

    public function getErrorsAsArray($form)
    {
        $errors = array();
        foreach ($form->getErrors() as $error) {
            $errors[] = $error->getMessage();
        }
        foreach ($form->all() as $key => $child) {
            if ($err = $this->getErrorsAsArray($child)) {
                $errors[$key] = $err;
            }
        }
        return $errors;
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants