Sorting Products
Learn to sort the products based on an attribute.
We can sort our products based on their price in the admin
and category
routes. We need to add the sorting buttons and sort the products in the controllers of these routes.
Adding sorting buttons
Let’s add ascending and descending sort buttons. We’ll also add a button to clear the sorting in our admin.hbs
and category/index.hbs
templates.
Adding buttons in the admin.hbs
template
Open the app/templates/admin.hbs
template and add the sort and clear buttons:
Press + to interact
{{!-- app/templates/admin.hbs --}}{{page-title "Admin"}}<br>{{!-- Create product div--}}<div class="row"><div class="col-4 add_edit"><LinkTo class='btn btn-success' @route="admin.add" >Add Product</LinkTo>{{!-- <LinkTo class='btn btn-success' @route="admin.edit" @model="123">Edit</LinkTo> --}}<hr>{{outlet}}</div><div class="col-8 products">{{!-- search div --}}<div class="row"><div class="col-md-8"><form class="form-inline"><div class="form-group" style="display: inline-block;">{{input type="text" class="form-control" value=filter id="search" placeholder="Search Products..."}}</div><div style="display: inline-block;"><button type="submit" {{action 'search'}} class="btn btn-primary">Search</button></div></form></div>{{!-- sorting div --}}<div class="col-md-4 sorting-div"><button class="btn btn-primary" type="button" {{action 'sortasc'}}>Sort Asc.</button><button class="btn btn-primary" type="button" {{action 'sortdsc'}}>Sort Dsc.</button><button class="btn btn-danger" type="button" {{action 'clear'}}>Clear</button></div></div>{{!-- search div end --}}{{!-- product div --}}<div class="row">{{#if this.appliedfilter }}{{#each filteredProducts as |item|}}<div class="col-lg-4 col-md-6 col-sm-6 col-12"><br><AdminProduct @source={{item.imglink}} @title={{item.product_title}} @desc={{item.desc}} @price={{item.price}} @route="admin.edit" @model={{item.id}}/></div>{{/each}}{{else}}{{#each @model as |item|}}<div class="col-lg-4 col-md-6 col-sm-6 col-12"><br><AdminProduct @source={{item.imglink}} @title={{item.product_title}} @desc={{item.desc}} @price={{item.price}} @route="admin.edit" @model={{item.id}}/></div>{{/each}}{{/if}}</div>{{!-- product div end --}}</div></div>
- Lines 31–36: We add a
div
of4-col
and three buttons.- Line 33: We add a button to sort the products in ascending order and attach a
sortasc
action to it. - Line 34: We add a button to sort the products in descending order and attach
- Line 33: We add a button to sort the products in ascending order and attach a