wintermeyer
wintermeyer

Reputation: 8318

Sort model by id

I sideload products of a given category. The problem is that they are not sorted. I'd like to sort them by id and render the sorted products in a select.

How can I sort them?

app/category/model.js

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  products: DS.hasMany('product', { async: true })
});

route.js

import Ember from 'ember';

export default Ember.Route.extend({
  model: function() {
    return {
      category: this.store.find('category', 1)
    };
  }
});

template.hbs

{{view "select" prompt="All products"
       content=model.category.products
       optionLabelPath="content.name"
       optionValuePath="content.name"
       value=selectedProduct
       class="form-control"}}

Upvotes: 1

Views: 348

Answers (1)

Patsy Issa
Patsy Issa

Reputation: 11293

You can use a computed property and the Ember.SortableMixin to sort the products in your controller:

sortedProducts: Ember.computed('model.category.products', function() {
  return Ember.ArrayProxy.createWithMixins(Ember.SortableMixin, {
    sortProperties: ['id'],
    sortAscending: true,
    content: this.get('model.category.products')
  });
})

And then simply use sortedProducts instead of model.category.products.

Source

Upvotes: 1

Related Questions