How to Sort Dataset in PCF Control?

By | May 21, 2021

Introduction

In this blog, we will see how we can sort records in the dataset in PCF control. The dataset object does have the property “sorting” which we can use to sort records according to a particular column in ascending or descending order.

Sort Dataset in PCF Control

To keep dataset designing simple and easy to understand we will be using the React Fluent UI framework’s “DetailList-Basic” control in our example. You can also use simple HTML, Javascript, and CSS for dataset grid as per the design.

As we are using DetailList, the ‘onColumnClick’ event has parameter that represents the column which is clicked. On this event, we can write the below code:

// when a column header is clicked sort the items
const _onColumnClick = (ev?: React.MouseEvent, column?: any): void => {
let dataset = props.pcfContext.parameters.sampleDataSet;
const newValue: any = {
name: column.fieldName,
sortDirection: column.isSortedDescending ? 0 : 1
}
while (dataset.sorting.length > 0) {
dataset.sorting.pop();
}
dataset.sorting.push(newValue);
(dataset.paging as any).loadExactPage(1);
dataset.refresh();
let isSortedDescending = !column?.isSortedDescending;
setItems(dataset.sorting);
setColumns(
columns.map(col => {
col.isSorted = col.key === column?.key;
col.isSortedDescending = isSortedDescending;
return col;
})
);
}

In the above code, we first need to get the current sorting direction of the selected column after which we can change it in the opposite direction. For example, if the current direction is ‘ascending’ then we will change it into ‘descending’ and vice versa. For that, we need to check dataset.sorting. To change the current SortStatus of the dataset column, we have to pass the object that contains the name (the name of the column) and sortDirection (the current sort direction of the column).

SORTDIRECTION

Value Member
-1 None
0 Ascending
1 Descending

After changing the SortStatus, we need to call dataset.refresh(), otherwise, there will be no desired effect.

Also, we have to navigate to the first page if we want that sorting to be applied to the entire dataset instead of applied only for dataset visible on the same page.

dataset.sorting.push(newValue);
(dataset.paging as any).loadExactPage(1);
dataset.refresh();

Conclusion

By using Sorting, we can easily sort records in the PCF control dataset for a particular column in ascending/descending order.

click2clone