dalgard / meteor-viewmodel

Minimalist VM for Meteor
24 stars 2 forks source link

Could binding with "Array Field" in "Auto Form"? #12

Closed thearabbit closed 8 years ago

thearabbit commented 8 years ago

I use array field in autoform and then I would like to sum of amount

// Schema
Items = new SimpleSchema({
   item: .......
   $.qty: ........
   $.price:........
   $.amount:..........

   totalAmount:..........
});
<template>
   ..............
   {{> afQuickField name="amount"}}
   ..............

  {{> afQuickField name="totalAmount"}}
</template>

Please help me.

dalgard commented 8 years ago

You should start by removing totalAmount from your schema – the total amount should always be calculated by summing the items. If the items are in an array, this can be done with reduce (see example below).

Now totalAmount is not a field anymore, so you simply need a helper to output the sum. You can get the state of the array field reactively from AutoForm with getFieldValue.

If the template already has a ViewModel instance on it, you can declare the helper there. Otherwise, just use a regular Blaze helper. The function looks the same:

Template.myForm.helpers({  // or viewmodel
  totalAmount: function () {
    var items = AutoForm.getFieldValue("items");

    return _.reduce(items, function (total, item) {
      return total + item.amount;
    }, 0);
  }
});
{{> afQuickField name='items'}}

Total: {{totalAmount}}
thearabbit commented 8 years ago

Thanks for your reply, I will try soon. But I don't understand how to use bind in

{{> afQickField ......... bin 'value: textName'}}
dalgard commented 8 years ago

You can not use {{bind}} this way, for a lot of reasons. You will see, when you become more experienced with Meteor.

Luckily, there's no real need for this use, because AutoForm is a viewmodel in itself.