ember-validations with ember-rapid-forms with backend auth

Have you ever wanted to have ember validations work with ember rapid forms all together with  errors you get back from rails?

And have you gone from blog post to blog post only to find outdated solutions?

Well this blog posts tries to do something about it.

so lets say you followed all the documentation and at present day you are left in situation where ember-validations mixin makes normal errors from ember model not work because it overwrote the errors object on the model in order to customise it.
Once you make rails return what is described in the ember error docs http://emberjs.com/api/data/classes/DS.Errors.html

you get it kinda half way so now rails part is ok and you touch nothing there.

only thing that is left it is to make validations work with native errors. We would like something seamless if possible.

so there are 3 methods in use by native ember errors that are needed for their normal operation

if we redirect them to do function on object that ember validation mixin uses then it is something that does the job.
so lets say you instantiate a model in a route that is an oportunity for patching it

model(){
  let user = this.store.createRecord('user');
  let x=user.get('errors');
  //first lets patch the add function
  x.add=function(k,v){
    //get the field on the error object that has errors for a field
    let xx = this.get(k);
    //add the error text to the array of errors for this specific field
    xx.pushObject(v[0].detail);
  }
  // if we want to remove error we just create fresh array that should hold errors for this specific field
  x.remove= function(k){this.set(k,Ember.A());}
  //once we want to clear all errors on all fields we loop trough all fields on error object and remove all messages from them
  x.clear= function(){
    let xx = this.get('errors');
    xx.forEach(function(k){x[k].unshift();});
  }
return user;
},

so error object that is created by ember validations has fields for each model field.
values of those fields are arrays with error messages
so email field can have array [’email already taken’]
so error object looks like this
{
email: [’email taken’]
}
keep in mind it is an ember object and not plain javascript it is also enumerable
now the thing should be working
 

 

Leave a Comment