JoshJoe
JoshJoe

Reputation: 1650

How can I use autoform to populate a select element with #each?

Here is part of my form that I'd like to convert to using autoform.

<div class="col-lg-4 col-md-4 col-sm-4">
<label for="pay_with" id="pay_with_label">Pay With</label>
<select name="pay_with" id="pay_with" class="form-control select select-primary mbl" required data-placeholder="Select an Option">
    <option value="Card">New Card</option>
    <option value="Check">New Bank</option>
    {{#each device}}
        <option value="{{card_id}}" selected {{selected}}>{{brand}} - {{last4}}</option>
    {{/each}}
</select>

In autoform, how do I translate this part?

{{#each device}}
    <option value="{{card_id}}" selected {{selected}}>{{brand}} - {{last4}}</option>
{{/each}}

Upvotes: 2

Views: 444

Answers (1)

georgedyer
georgedyer

Reputation: 2745

Create a template helper function that returns the options array for your select menu, by mapping your devices array and adding in the extra options in order to get the proper schema for autoform, like so:

Template.myForm.helpers({
   deviceOptions: function() {

      var deviceOpts = devices.map(function(device) {
         return { label: device.brand+' - '+device.last4, value: device.card_id }
      });

      deviceOpts.unshift({ label: 'New bank', value: 'Check' });
      deviceOpts.unshift({ label: 'New card', value: 'Card' });

      return deviceOpts;
   },
});

Then, you can call the helper in your template directive:

{{> afFieldInput name="payWith" type="select" options=deviceOptions }}

Upvotes: 2

Related Questions