Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember Data 1.0.0: how to retrieve validation errors (422 response)

I am converting from Ember data 0.13 to 1.0.0 Beta 1. In 0.13, I was using the becameError and becameInvalid states to know whether there was a problem when saving a record.

In 1.0.0 there is no longer a transaction and you need to use the save promise to handle errors. See below:

 save: function() {
    this.get('model').save().then(function () {
        alert("Record saved");
      }, function () {
        alert("Problem");
      });
    }, 

In the above, I want to make a distinction between validation errors and all the rest (just as it was before in 0.13 with becameError and becameInvalid).

Is there a way to access the error object and how to read the validation errors included in the json response ? Before this was via this.get('content.errors') ...

Hoep somebody can help Marc

like image 473
cyclomarc Avatar asked Apr 19 '26 12:04

cyclomarc


1 Answers

Three steps:

Return errors in a proper format. If it Rails application, then:

\# Rails controller, update function

format.json { render json: {errors: @post.errors.messages}, status: :unprocessable_entity }

Set errors in promise

// app.js
save: function() {
  self = this;
  this.get('model').save().then(function () {
    alert("Record saved");
  }, function (response) {
    self.set('errors', response.responseJSON.errors);
  });
}

Display errors in a handlebar template

<\!-- index.html -->
{{input type="text" value=title}}<span class="alert-error">{{errors.title}}</span>
like image 166
denis.peplin Avatar answered Apr 22 '26 22:04

denis.peplin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!