如何将查询参数的值传递给表单?

时间:2015-01-19 10:52:21

标签: ember.js ember-data ember-cli ember-cli-pods

我的网址看起来像http://localhost:4099/checkout/schedule/new?addressId=12我正在尝试将查询参数addressId传递给表单。

我尝试将其作为隐藏输入提交,但是当它到达save动作时。我检查了Ember检查员的Network标签,这就是它传递的内容:

{"delivery":{"instructions":"foo","deliver_on":"bar","address_id":null}}

address_id仍为null。我错过了什么?

以下完整代码:

// app/pods/checkout/schedule/new/route.js
import Ember from 'ember';

export default Ember.Route.extend({
  model: function() {
    return this.store.createRecord('delivery');
    // return this.store.createRecord('delivery', { addressId: this.get('addressId')});
  },
  // Cleanup the controller, when you leave the new route so the stale new record is also
  // removed from the store.
  // You can also use https://github.com/dockyard/ember-data-route instead
  resetController: function (controller, isExiting) {
    var model = controller.get('model');

    if (!model.get('isDeleted') && isExiting && model.get('isNew')) {
      model.deleteRecord();
    } else {
      model.rollback();
    }
  }
});

// app/pods/checkout/schedule/new/controller.js
import Ember from 'ember';

export default Ember.Controller.extend({
  queryParams: ['addressId'],
  addressId: null,

  actions: {
    save: function() {
      var _this = this;

      // this.get('model').set('addressId', this.get('addressId'));
      this.get('model').save().then(function(){
        _this.transitionToRoute('checkout.address.index');
      }, function() {
        // Need this promise, so we can render errors, if any, in the form
      });

      return false;
    },
    cancel: function() {
      return true;
    }
  }
});

// app/pods/checkout/schedule/new/template.hbs
<form {{action "save" on="submit"}}>
  {{addressId}}
  {{input type="hidden" value=addressId}}

  <p>
    <label>Instructions:
      {{input value=model.instructions}}
    </label>

    {{#each error in errors.instructions}}
      <br />{{error.message}}
    {{/each}}
  </p>

  <p>
    <label>Deliver on:
      {{input value=model.DeliverOn}}
    </label>

    {{#each error in errors.DeliverOn}}
      <br />{{error.message}}
    {{/each}}
  </p>

  <input type="submit" value="Next"/>
  <button {{action "cancel"}}>Cancel</button>
</form>

// app/models/delivery.js
import DS from 'ember-data';

export default DS.Model.extend({
  address:      DS.belongsTo('address', { async: true }),
  items:        DS.hasMany('item', { async: true }),
  instructions: DS.attr('string'),
  deliverOn:    DS.attr('string')
});

1 个答案:

答案 0 :(得分:0)

我相信发生的事情是你并没有真正提交你的表格。相反,您在模型上调用save(),它会提交您的模型数据。因此,表单中的隐藏参数对您没有帮助。

网址中的addressId控制器中的addressId媒体资源相关联,而您在Chrome中提交的addressId: null就是模型

addressId属性的值