Reputation: 7230
In an application built with Ember 2.1.0, I followed this guide to implement server side validation.
I have this route :
import Ember from 'ember';
export default Ember.Route.extend({
model(params) {
return this.store.findRecord('user', params.id);
},
actions: {
submit: function() {
this.controller.model.save().then(function() {
this.transitionTo('admin.users');
}, (data) => {
console.log(data.errors);
this.set('errors', data.errors);
});
},
cancel: function() {
this.controller.model.rollbackAttributes();
this.transitionTo('admin.users');
}
}
});
And I have this code in the template :
{{#if errors.length}}
<div class='alert alert-danger'>
<h4>There was a problem</h4>
<p>The user could not be saved due to validation errors</p>
</div>
{{/if}}
The server returns {"errors":[{"email":["can't be blank"]}]}
and errors are displayed in the console but nothing on the page.
According to the documentation, I tried to return {"errors":{"email":["can't be blank"]}}
but I have "InvalidError
expects json-api formatted errors array."
How can I show errors with Ember 2?
Upvotes: 0
Views: 107
Reputation: 7230
I finally found the solution. The data sent by the server was not using the json API format as written in the doc like this :
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/vnd.api+json
{
"errors": [
{
"status": "422",
"source": { "pointer": "/data/attributes/first-name" },
"title": "Invalid Attribute",
"detail": "First name must contain at least three characters."
}
]
}
I wrote this code, in ruby, to format it correctly :
class ErrorSerializer
def self.serialize(errors)
result = errors.messages.map do |message|
message.last.map do |detail|
{
"source": { "pointer": "/data/attributes/#{message.first}" },
"detail": detail
}
end
end.flatten
{ errors: result }
end
end
I can be used like this :
render status: :unprocessable_entity, json: ErrorSerializer.serialize(user.errors)
Upvotes: 1