indexiatech / ember-forms

Smart, Intuitive forms for Ember.js styled with Bootstrap, Multi layouts and Validation support.
http://indexiatech.github.io/ember-forms
Apache License 2.0
218 stars 45 forks source link

Programmatically add an error #81

Open karellm opened 9 years ago

karellm commented 9 years ago

I have a signup form, that performs some validation on the server (is the email already taken). When I get the server response, I set a flad emailTaken and run an inline validator:

import Ember from 'ember';
import EmberValidations from 'ember-validations';

export default Ember.ObjectController.extend(EmberValidations.Mixin, {
  validations: {
    email: {
      presence: true,
      inline: EmberValidations.validator(function () {
        if (this.model.get('emailTaken')) {
          return 'email already taken';
        }
      })
    }
  },
  actions: {
    signUp: function () {
      var self = this;
      Ember.$.ajax({
        //...
      }).then(
        function (response) {
          self.model.setProperties(response.user);
          self.transitionToRoute('sessions/confirmation');
        },
        function (response) {
          if (response.responseJSON.errors.indexOf('email_taken') !== -1) {
            self.set('emailTaken', true);
            self.set('error', 'Damn fuck');
          }
          self.validate(); // validates fine but doesn't rerender the form
        }
      );
    }
  }
});

So the validation runs fine but the form doesn't re-render. Can I do that manually, or bind it to the validation?

xcskier56 commented 9 years ago

Hi @karellm, I hope you've figured this out by now, but in case you haven't I ran across the same issue, and this is how I solved it

actions: {
  saveInvite: function() {
    var self = this;
    var onSaveSuccess = function(response) {
      // ...
    };
    var onSaveFailure = function(response) {
      var errors = response.errors
      var errorKeys = Object.keys(errors);
      for (var i = 0; i < errorKeys.length; i++) {
        var s = 'errors.' + errorKeys[i];
        self.model.set(s, [errors[errorKeys[i]]]);
      }
    };
    self.model.save().then(onSaveSuccess, onSaveFailure);
  }
}

In a nutshell, I get the errors back from the server, and then get the error keys from Object.keys(errors), then I loop through the errors and add them to the model by hand.

Note that in model.set('errors.email', ['Email is already taken']) I pass an array because otherwise the validation message is nill.

karellm commented 9 years ago

Thanks @xcskier56 I will try that. I actually think I will go with easy form though as soon as they roll the v2.