It's relatively easy to create a select in Ember.js using Ember.Select.
The question is, how do I make this into a grouped select, using an optgroup. I don't think this is built in, but I'm guessing it's possible with some modifications to the template.
This is natively supported by Ember now, but there are a few gotchas. In 1.4.0, the following solution works...
Here's the example data:
foos: Ember.A([{value: 'foo', label: 'Foo', group: 'Foos'}, {value: 'bar', label: 'Bar', group: 'Bars'}, {value: 'bar2', label: 'Bar2', group: 'Bars'}, {value: 'foo2', label: 'Foo2', group: 'Foos'}])
Here's the view helper:
{{view Ember.Select content=controller.foos optionLabelPath='content.label' optionValuePath='content.value' optionGroupPath='group'}}
If, you just do the above you will get a select list that looks like this:
The only way I could get around this was to sort the array first by the grouped field:
foos: Ember.A([{value: 'foo', label: 'Foo', group: 'Foos'}, {value: 'bar', label: 'Bar', group: 'Bars'}, {value: 'bar2', label: 'Bar2', group: 'Bars'}, {value: 'foo2', label: 'Foo2', group: 'Foos'}]).sortBy("group")
Here's the solution that I came up with. https://gist.github.com/3297425
I had to make two collections. One grouped and the other just content so that the proper option can be selected.
groupedServiceCodes = [Ember.Object.create({label: 'Label for optgroup', content: Ember.A()}), …]
And then flatten the content from groupedServiceCodes down to maintain order for the select:
flattenedServiceCodes = [].concat(object.get('content'), …)
This is a bit of a hack, and I think Ember is wanting for a better solution, but this works for me. I would love to hear thoughts on improving this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With