Skip to content
Duncan Walker edited this page Jul 18, 2015 · 6 revisions

Saving and validating models is easy.

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
    submitText='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);
    });
  },

});

Running Custom Validations

You can run custom validations for model tests that aren't supported by Ember.Validations:

// app-name/controllers/posts/new.js

import Ember from 'ember';
import FormMixin from 'ember-easy-form-extensions/mixins/controllers/form';

export default Ember.Controller.extend(
  FormMixin, {

  runCustomValidations() {
    return new Ember.RSVP.Promise(function(resolve, reject) {
      /* Run some kind of validations Ember.Validations doesn't support

      resolve() to validate the model successfully
      reject() to validate the model unsuccessfully
      */

      if (this.get('someContent').mapBy('id').indexOf(5) > -1) {
        resolve(); // Continue
      } else {
        reject(); // Fail
      }
    });
  },

  save() {
    /* Runs after validations pass and submit is clicked */
    
    this.get('model').save()...
  },

});

runCustomValidations must return a promise.

Handling Cancel

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');
  },
});

Rolling Back Records

To handle the automatic deletion of a new record or rollback of an existing record with unsaved changes, add the DirtyRecordHandlerMixin to your route:

// app-name/controllers/fruits/new.js

import Ember from 'ember';
import DirtyRecordHandlerMixin from 'ember-easy-form-extensions/mixins/routes/dirty-record-handler';

export default Ember.Route.extend(
  DirtyRecordHandlerMixin, {

  model() {
    return this.store.createRecord('fruit');
  },
});
Clone this wiki locally