Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Grouped Select in Ember.js

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.

like image 700
Tony Pitale Avatar asked Aug 06 '12 22:08

Tony Pitale


2 Answers

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:

enter image description here

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")

enter image description here

like image 102
steakchaser Avatar answered Oct 04 '22 23:10

steakchaser


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.

like image 21
Tony Pitale Avatar answered Oct 05 '22 01:10

Tony Pitale