lightning datatable header level actions

lwc Apr 06, 2020

Header-level actions helps to perform data manipulations like filtering/ manipulating table data. You can perform actions on a column header and handle them using the onheaderaction event handler.

In this post we're going build Cases LWC which can be filtered by Status and Priority as shown below

Note In the above example Status and Priority filter works independently

Here is the quick look of cases.html


<lightning-datatable key-field="id" data={cases} columns={columns} 
					 hide-checkbox-column
                     onheaderaction={handleHeaderAction}>
</lightning-datatable>

In above html onheaderaction event  is responsible for handling heading level selection

And here is  handleHeaderAction handler in cases.js

handleHeaderAction(event) {
    // gives the selection header action name
    const actionName = event.detail.action.name;
    
    // gives selected column definition
    const colDef = event.detail.columnDefinition;
    
    // assigning colmuns to new variable
    let cols = this.columns;

    if (actionName !== undefined && actionName !== 'all') {
        // filtering cases on selected actionname
        this.cases = this.ALL_CASES.filter(_case => _case[colDef.label] === actionName);
    } else if (actionName === 'all') {
        // returning all cases
        this.cases = this.ALL_CASES;
    }

    /* Following line is responsible for finding which header action selected and return corresponding actions then we will mark selcted as checked/true and remaining will be marked as unchecked/marked */
    
        cols.find(col => col.label === colDef.label).actions.forEach(action => action.checked = action.name === actionName);
        this.columns = [...cols];
    }

Other important items to discuss will in the post are,

  1. For getting Status picklist values dynamically - click here  for salesforce reference
  2. Getting all cases using Apex controller

Getting cases using Apex Controller

Syntax for importing ApexClass will be like,

import getCases from '@salesforce/apex/cases.getCases';
NOTE: cases is class name while getCases is method
@wire(getCases)
    wiredCases({ error, data }) {
        if (data) {
            this.ALL_CASES = data;
            this.cases = data;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.contacts = undefined;
        }
    }

Above wire method is responsible for assigning getCases results to ALL_CASES variable

Here is the link for the actual demoed LWC

Phanindra Mangipudi

Salesforce, Lightning Web Componets, Node.Js, Angular 2+, Bootstrap