ng-admin

ng-admin - Displaying form validation errors from the server


Sorry if this is documented somewhere but I haven't been able to find it. Is there a way to specify field errors after a create/update fails validation on the server? Does ng-admin have any features to highlight the fields with errors? Should I format my error response in a specific way?

EDIT: Should mention that I've already configured error display through app.errorMessage(), just wondering if there's additional form field highlighting features.


Solution

  • The next version of ng-admin makes it possible usinf creation and edition hooks (refs https://github.com/marmelab/ng-admin/pull/898):

    For instance, a POST /comment REST endpoint may return with an HTTP error code if the post_id pointed by the new comment doesn't exist.

    POST /comment
    {
        body: 'Commenting on a non-existent post',
        post_id: 123
    }
    
    HTTP 1.1 400 Bad Request
    [
        { propertyPath: 'post_id', message: 'Related post does not exist' }
    ]
    

    To catch these errors and display them, use the editionView.onSubmitError() and creationView.onSubmitError() hooks. They accept an angular injectable (a function listing its dependencies), and ng-admin can inject the error response, the form object, and many other useful services.

    comment.editionView().onSubmitError(['error', 'form', 'progression', 'notification', function(error, form, progression, notification) {
        // mark fields based on errors from the response
        error.violations.forEach(violation => {
            if (form[violation.propertyPath]) {
                form[violation.propertyPath].$valid = false;
            }
        });
        // stop the progress bar
        progression.done();
        // add a notification
        notification.log(`Some values are invalid, see details in the form`, { addnCls: 'humane-flatty-error' });
        // cancel the default action (default error messages)
        return false;
    }]);