Sorting a table in the back office

hey @darrenhunterEmerald

uui-table is just a display component it renders rows/cells but doesn’t have any built-in sorting, so you’ll need to wire that up yourself.

If you tried using the Sorter and couldn’t get it working, that’s probably because it’s not actually for this — UmbSorterController is for drag-and-drop reordering of a list, not for sorting a column by clicking its header. Different problem, so it won’t help here.

For click-to-sort-a-column, handle it the same way you handled paging by attaching listeners after the markup is in the DOM, not inside the string-building functions themselves:

  1. Give each header cell an identifiable attribute in tableHeader(), e.g. <uui-table-head-cell data-field="name" role="columnheader">Name</uui-table-head-cell>.
  2. After render (alongside your setupPaging() call), add a setupSorting() function that grabs the header cells from _root and attaches click listeners:

js

function setupSorting() {
    var headers = _root.querySelectorAll("uui-table-head-cell[data-field]");
    headers.forEach(function (header) {
        header.addEventListener("click", function () {
            sortData(header.getAttribute("data-field"));
        });
    });
}
  1. Write sortData(field) to toggle direction and sort _data directly:

js

let _sortColumn = null;
let _sortDirection = "asc";

function sortData(field) {
    if (_sortColumn === field) {
        _sortDirection = _sortDirection === "asc" ? "desc" : "asc";
    } else {
        _sortColumn = field;
        _sortDirection = "asc";
    }

    _data.sort((a, b) => {
        const valA = a[field];
        const valB = b[field];
        if (valA < valB) return _sortDirection === "asc" ? -1 : 1;
        if (valA > valB) return _sortDirection === "asc" ? 1 : -1;
        return 0;
    });

    _currentPage = 1;
    clearTable(buildtable(_currentPage));
}
  1. Call setupSorting() again after clearTable() rebuilds the markup, since the old header elements (and their listeners) get wiped out along with the rest of the table’s innerHTML.
  2. Also call setupSorting() once in loadData(), right next to your existing setupPaging() call otherwise the first render won’t have any listeners attached at all.