Skip to content

Instantly share code, notes, and snippets.

@loadx
Created November 14, 2012 00:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loadx/4069289 to your computer and use it in GitHub Desktop.
Save loadx/4069289 to your computer and use it in GitHub Desktop.
Ember-data server side validation without deadlocking the record as 'invalid'
App.AddContactController = Em.ArrayController.extend({
init: function(){
this.companies = App.store.findAll(App.Company);
},
beginEdit: function(){
// By default createRecord will add this to the ArrayProxy and it will be rendered
// this property allows us to toggle rendering
this.set('record', App.store.createRecord(App.Contact, {'visible': false}));
},
save: function(){
this.get('record').addObserver('stateManager.currentState.name', function(){
var currentState = this.get('stateManager.currentState.name');
if(currentState === 'saved'){
// once the record was successfully saved we will render it
this.set('visible', true);
this.set('errors', []);
}
});
App.store.commit();
}
});
In the adapter somewhere:
createRecord: function(store, type, record){
var root = this.rootForType(type);
var data = {};
data = this.toJSON(record, { includeId: true });
this.ajax(this.buildURL(root), "POST", {
data: data,
context: this,
type: 'json',
statusCode: {
400: function(json){
if(json.responseText.length > 0){
store.recordWasInvalid(record, $.parseJSON(json.responseText));
record.get('stateManager').send('becameValid');
}
}
},
success: function(json) {
this.didCreateRecord(store, type, record, json);
}
});
}
@KasperTidemann
Copy link

+1 - this is very useful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment