mardi 12 avril 2016

Reset form after saving a model so that it only allows to create objects

I have a sign up form that i need to fill up and reset after saving the model data. The issue is that ember will fire a PUT request after creating to every subsequent requests. How can i change this to POST only requests. Also i would like to know how to access message i get back from the server in the succeeded promise.

component.hbs

<form {{action "register" user on="submit"}}>
  <div class="form-group">
    <label for="email">Email</label>
    {{input value=user.email 
      placeholder="Email" 
      id="email" 
      class="form-control"}}
    <small>{{errors.error-email}}</small>
  </div>

 <div class="form-group">
   <label for="password">Password</label>
   {{input value=user.password 
     type="password" 
     placeholder="Password" 
     id="password" 
     class="form-control"}}
   <small>{{errors.error-password}}</small>
 </div>

 <div class="form-group">
   <label for="passwordConfirmation">Password Confirmation</label>
   {{input value=user.passwordConfirmation 
     type="password" 
     placeholder="Password Confirmation" 
     id="passwordConfirmation" 
     class="form-control"}}
   <small>{{errors.error-password_confirmation}}</small>
 </div>
 <button type="submit" 
      class="btn btn-default" 
      Submit
 </button>
</form>
<br>

{{#if responseMessage}}
  <div class="alert alert-danger">{{responseMessage}}</div>
{{/if}}

component.js

export default Ember.Component.extend({
  actions: {
    register(params) {
      this.sendAction('action', params);
    }
  }
});

route.js

export default Ember.Route.extend(UnauthenticatedRouteMixin, {  
  model() {
    return this.store.createRecord('user');
  },

  actions: {
    saveUser(newUser) {
      newUser.save().then((resp) => {
        // RESET FORM AND GET RESP BACK
        this.controller.set('responseMessage', 'User has been created     successfully!');
      }).catch((reason) => {
        let errors = {};
        reason.errors.forEach((error) => {
          errors[`error-${error.field}`] = error.messages[0];
        });
        this.controller.set('errors', errors);
      });
    }
  }
});

sign-up.hbs

{{users.sign-up-form 
  user=model 
  errors=errors 
  responseMessage=responseMessage 
  action='saveUser'}}

Aucun commentaire:

Enregistrer un commentaire