保存模型后重置表单,以便只允许创建对象

时间:2016-04-12 16:07:56

标签: javascript ember.js

我有一个注册表单,我需要在保存模型数据后填写并重置。问题是,在创建每个后续请求后,ember将触发PUT请求。如何将此更改为仅POST请求。此外,我想知道如何访问消息,我在成功的承诺中从服务器返回。

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

签up.hbs

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

1 个答案:

答案 0 :(得分:0)

this.controller.set('responseMessage', 'User has been created successfully!');

您可能想要添加以下行:

this.controller.set('model', this.store.createRecord('user')

这会将控制器的型号重置为新记录。此外,访问回复的消息就像resp.message一样,如果它是JSON。