-
Notifications
You must be signed in to change notification settings - Fork 14
3. Saving Models
Saving and validating models is easy.
- [Handling cancel](#handling cancel)
- Intercepting save and cancel methods
- Undoing dirty records
Setup your template and, if desired, customize the submit button text:
{{!--app-name/templates/fruits/new.hbs--}}
{{#form-wrapper}}
{{#form-controls}}
{{input-group property='name'}}
{{/form-controls}}
{{form-submission
saveText='Save'
}}
{{/form-wrapper}}
Then add your save logic to the controller:
// app-name/controllers/fruits/new.js
import Ember from 'ember';
import FormMixin from 'ember-easy-form-extensions/mixins/controllers/form';
export default Ember.Controller.extend(
FormMixin, {
validations: {
'model.name': {
presence: true
}
}
cancel: function() {
this.transitionTo('fruits');
},
save: function() {
this.get('model').save().then(function(fruit) {
this.transitionTo('fruit', fruit);
});
},
});
By default {{form-submission}}
adds a cancel button to your form. You can disable this by setting cancel=false
:
{{form-submission}} {{!-- Cancel button --}}
{{form-submission cancel=false}} {{!-- No cancel button --}}
The cancel()
hook in your controller will be called when the user clicks the cancel button:
// app-name/controllers/fruits/new.js
import Ember from 'ember';
import FormMixin from 'ember-easy-form-extensions/mixins/controllers/form';
export default Ember.Controller.extend(
FormMixin, {
cancel() {
this.transitionToRoute('fruit');
},
});
Each method, cancel
, delete
, and save
, can be intercepted using a beforeX
handler, where X
is the capitalized name of the action. This handler should return a promise that either resolves to let the subsequent method be called or rejects to block the call.
// app-name/controllers/fruits/new.js
import Ember from 'ember';
import FormMixin from 'ember-easy-form-extensions/mixins/controllers/form';
export default Ember.Controller.extend(
FormMixin, {
beforeCancel() {
return new Ember.RSVP.Promise(function(resolve, reject) {
if (this.get('model.isDirty')) {
this.showConfirmation();
reject();
} else {
resolve();
}
});
},
cancel() {
this.transitionToRoute('fruits');
},
});
To handle the automatic deletion of a new record or rollback of an existing record with unsaved changes, add the UndoDirtyRecordMixin
to your route:
// app-name/routes/fruits/new.js
import Ember from 'ember';
import UndoDirtyRecordMixin from 'ember-easy-form-extensions/mixins/routes/undo-dirty-record';
export default Ember.Route.extend(
DirtyRecordHandlerMixin, {
model() {
return this.store.createRecord('fruit');
},
});