Default value in select Ember js

681 Views Asked by At

Hello guys I have model Currency. I have fields name:string, default:boolean. In my db only one record can have default value and i want this record was selected in select tag.

Example:

name: Eur default:false

name: USD default: true

name: RUR default: false

I want to have :

<selected>
  <option>Eur</option
  <option selected=selected>USD</option
  <option>RUR</option
</selected>

Route.js

EmberMoney.IncomesRoute = Ember.Route.extend
  model: ->
    EmberMoney.Income.find()
  setupController: (controller) ->
    controller.set('currencies', EmberMoney.Currency.find());

incomes.handlebars

// Some output with Incomes records

{{view Ember.Select
       contentBinding="controller.currencies"
       optionLabelPath="content.name"
       optionValuePath="content.id"}}
1

There are 1 best solutions below

1
Christopher Swasey On

You can subclass Ember.Select and override selection as such:

EmberMoney.Select = Ember.Select.extend({
    selection: Ember.computed(function (key) {
      var content = this.get('content');
      if (!content || !content.length) return null;

      return content.findProperty('default', true)
    }).property('content.[]')
});

Because selection in your subclass doesn't have a value parameter, the computed property will get permanently replaced for that instance as soon as the selection is changed.

Note that if you set up a binding for selection, selection will be overridden almost immediately, and you'll instead have to define this property on the source object or get more complicated:

EmberMoney.Select = Ember.Select.extend({
    selection: Ember.computed(function (key, value) {
      if (value === undefined || Ember.isNone(value)) {
          var content = this.get('content');
          if (!content || !content.length) return null;

          return content.findProperty('default', true)
      } else {
        return value;
      }
    }).property('content.[]')
});