SAPUI5: How to Use the Sorter in an XML View or Controller?

This is how to use the sorter in SAPUI5.

Both in an XML view and a controller.

So if you want to learn how to use the sorter in SAPUI5, here is the article for you.

Let’s get started!

What Is the Sorter in SAPUI5?

Sorter sorts and groups items in an SAPUI5 control.

For example, a sorter can sort items ascending or descending according to their values. And sorters can group items based on their value.

For example, in a list control—below you see a list’s items grouped and sorted descending by a s’s binding.

The products are grouped by the products supplier’s name and sorted ascending by the products name in each group:

sapui5_sorter_grouped_list_screenshot
[sap]

A sorter can be set to a control’s binding in:

  • An XML view
  • A controller

Keep in mind that in an XML view the sorter is supposed to be static.This implies that the sorter shouldn’t change over time—for instance, a list should be sorted the same way from the start to the end of the application.

On the other hand, a dynamic sorter is supposed to be set in a controller.This means the sorter changes throughout the application life cycle. For example, the application has a button that when clicked switches the list from descending to ascending order.

Here’s how to set them in an XML view, in a controller:

Set a Sorter in an XML View in SAPUI5

Use an XML view to set up an initial and static sorter for a control like a list:

<!-- in your XML view -->
 
...
 
<List
  items="{
 
    path: '/Products', 
     
    sorter: [
 
      {
        path: 'Supplier', 
        descending: 'false', 
        group: 'true'
      }

    ]
   
  }">
  <items>
     
    <StandardListItem
      title="{ProductName}"
      description="{ProductId}"/>
   
  </items>
</List>
 
...

Set a Sorter in a Controller in SAPUI5

Set a dynamic sorter for a control like a list using a controller:

// in your controller
...   

  var oSorter = new Sorter({

    path: "Supplier", 
    descending: false, 
    group: true

  });  

  var oList = this.byId("list-id");

  oList.getBinding("items").sort(oSorter);

...

Voila.

By the way, do you know how to send custom data to a controller from an XML view? From a controller to an XML view is easy but the other way around? If you want to learn how to pass data from an XML view to a controller take a look at this article that explains how to pass any data from an XML view to a controller in SAPUI5.

Leave a Comment