vendredi 9 janvier 2015

Ember DS.Errors troubleshooting on create form.

I have a basic create form setup which has validation on the name field. The save action for the form has a promise to gracefully hold the error:



actions: {
save: function(){

var route = this;

var createCampaign = this.store.createRecord("campaign", {

code: this.get("code"),
name: this.get("name"),
description: this.get("description"),

});

this.set("code",""),
this.set("name",""),
this.set("description",""),

// POST values to campaigns

createCampaign.save().then(function(c){

route.transitionToRoute("campaigns.view",c.id);

}, function(errors){


});
}
}

});


My defining attributes is:



TM.Campaign = DS.Model.extend({
name: DS.attr(),
code: DS.attr(),
description: DS.attr(),

});


I've read that by using a RESTAdapter, the ajaxError needs to be overwritten, so I've added the following:



ajaxError: function(jqXHR){

var error = this._super(jqXHR);

if(jqXHR && jqXHR.status === 422){

var response = Ember.$.parseJSON(jqXHR.responseText);

errors = {}

if (response.errors){

var jsonErrors = response.errors;

Ember.keys(jsonErrors).forEach(function(key){
errors[Ember.String.camelize(key)] = jsonErrors[key]
});

}

return new DS.InvalidError(errors)

} else {

return error

}

}


The response which is coming from the API is structured as:



{

"errors": {
"name": [
"The name field is required."
]
}

}


But for some reason, whenever I try to display DS.Errors (using console.log(route.get("errors")), I get undefined. It's like Ember doesn't know that a validation error has appeared within the response.


I've also made sure that the response status comes back as 422 Unprocessable Entity. Can anyone see what I'm missing??





Aucun commentaire:

Enregistrer un commentaire