Сохранение имеет много отношений с формой - PullRequest
0 голосов
/ 19 февраля 2019

У меня возникли проблемы при сохранении формы с отношениями hasMany.Все работает нормально, когда я обновляю существующие варианты продукта.Проблема возникает, когда я хочу создать новый продукт или обновить существующий, добавив новые варианты для каждого.Чего я хочу достичь?Как видите все мои варианты продукта отображаются в таблице.Я хотел бы создать новый productVariant, нажав кнопку, которая вызывает действие «addVariant» и динамически добавляет новую строку в существующую таблицу с возможностью заполнения входных данных.Все новые варианты должны быть отправлены на сервер при отправке формы.Не могли бы вы дать мне какие-нибудь советы или немного поработать?Я совершенно новичок в EmberJS и JS в целом, и такая помощь определенно уменьшит мои усилия в процессе обучения.Ниже приведен код.

Модели:

export default DS.Model.extend(Validations, {
  uniqueId: DS.attr('string'),
  name: DS.attr('string'),
  defaultPrice: fragment('price'),
  venue: DS.belongsTo('venue'),
  deleted: DS.attr('boolean'),
  productType: DS.attr('string'),

  productCategory: DS.belongsTo('product-category', {async: false}),
  productVariants: DS.hasMany('product-variant', {async: false}),
});

export default DS.Model.extend({
  uniqueId: DS.attr('string'),
  name: DS.attr('string'),
  fullName: DS.attr('string'),
  price: fragment('price'),
  weighted: DS.attr('boolean'),
  openPrice: DS.attr('boolean'),

  product: DS.belongsTo('product')
});

Форма выпуска:

export default Component.extend({
  store: service(),

  categories: computed(function(){
    return this.store.findAll('product-category', {
    });
  }),

  init() {
    this._super(...arguments);
    this.productTypes = ['PRODUCT_WITH_RECEPTURE', 'SET_AS_ONE_ITEM', 'SET_AS_SEPARATE_ITEMS', 'PIZZA'];
    this.currencies = ['PLN', 'EUR', 'USD'];
  },


  actions: {
    chooseCategory(category){
      let product = this.get('model');
      product.set('productCategory', category);
      this.set('productCategory', category);
    },

    chooseProductType(option){
      let product = this.get('model');
      product.set('productType', option);
      this.set('productType', option);
    },

    chooseCurrency(currency){
      let product = this.get('model');
      product.set('defaultPrice.currency', currency)
      this.set('currency', currency)
    },

    saveProduct(param){
      this.sendAction('action', param);
    }
  }
});

И его компонент:

<div class="form-horizontal">
  <div class="col-sm-10">
    {{#validated-input model=model valuePath='name' placeholder='Nazwa'}}{{/validated-input}}
  </div>
  <div class="col-sm-10">
    {{#validated-input model=model valuePath='defaultPrice.amount' placeholder='Koszt'}}{{/validated-input}}
  </div>
  <div class="col-sm-10">
    <div class="form-group">
      <label class="col-sm-2 control-label">Kategoria</label>
      {{#power-select
        selected=model.productCategory
        options=categories
        onchange=(action "chooseCategory") as |productCategory|}}
        {{productCategory.name}}
      {{/power-select}}
    </div>
  </div>
  <div class="col-sm-10">
    <div class="form-group">
      <label class="col-sm-2 control-label">Waluta</label>
      {{#power-select
        options=currencies
        selected=model.defaultPrice.currency
        onchange=(action "chooseCurrency") as |currency|}}
        {{currency}}
      {{/power-select}}
    </div>
  </div>
  <div class="col-sm-10">
    <div class="form-group">
      <label class="col-sm-2 control-label">Typ produktu</label>
      {{#power-select
        options=productTypes
        selected=model.productType
        onchange=(action "chooseProductType") as |productType|}}
        {{productType}}
      {{/power-select}}
    </div>
  </div>
  {{#product/product-variant-form item=model}}{{/product/product-variant-form}}
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="submit" class="btn btn-primary" {{action 'saveProduct' model}}>Zapisz</button>
    </div>
  </div>
</div>

Вариант изделияформа:

<legend>Warianty</legend>
<table class="table table-hover">
  <thead>
  <tr>
    <th>Nazwa</th>
    <th>Cena</th>
    <th>Dostępność</th>
  </tr>
  </thead>
  <tbody>
  {{#each item.productVariants as |productVariant|}}
    <tr>
      <th>{{input type="text" value=productVariant.fullName class="form-control"}}</th>
      <th>{{input type="text" value=productVariant.price.amount class="form-control"}}</th>
      <th class="center-check-box">{{input type="checkbox" checked=productVariant.openPrice class="form-control"}}</th>
    </tr>
  {{/each}}
  <button {{action 'addVariant'}}>Dodaj wariant</button>
  </tbody>
</table>

и ее составляющая:

export default Component.extend({

  store: service(),

  init() {
    this._super(...arguments);
    this.variants = [];
  },

  actions: {
    addVariant() {
      let product = this.get('model');
      console.log(product);
      let variant = this.store.createRecord('product-variant', {
        name: '',
        price: this.get('store').createRecord('price')
      });
      this.get('variants').pushObject(variant);
    }
  }
});

1 Ответ

0 голосов
/ 05 марта 2019

Похоже, вы не связываете свой вариант с вашим продуктом и не сохраняете его впоследствии.В документации Ember есть пример .Должно быть что-то вроде этого:

let product = this.get('model');
let variant = this.store.createRecord('product-variant', {
  name: '',
  price: this.get('store').createRecord('price')
});

product.get('productVariants').pushObject(variant);

variant.save().then(function () {
  product.save();
});
...