You are currently viewing Row-Level Actions in Datatable in Lightning Web Component -LWC

Row-Level Actions in Datatable in Lightning Web Component -LWC

  • Post author:
  • Post category:Salesforce

In this blog post, we will learn how to handle Row-Level actions in Lightning Datatable in Lightning Web Component (LWC).

Acceptance Criteria: Create a lightning datatable that will display all the product details. The product details component should have 2-Row Level actions.

  1. Show Details – When the user clicks on the button, it should take the user to the product details page (record page).
  2. Delete – When the user clicks on the button, it should delete the product from the database.

Row Level Action in Datatable in LWC:

RowLevelAction.Controller

public class ProductClass
    @AuraEnabled(cacheable = true)
    public static List<Product2> getProductDetails()
        List<Product2> prodList = [SELECT Name, ProductCode, Family, IsActive, Description FROM Product2];
        return prodList;


RowLevelActionComp.html

<template>
    <lightning-card title="Row Level Action on Product" icon-name="standard:product"> <br/>
        <template if:true=data>
            <lightning-datatable key-field="Id" data=data columns=columns onrowaction=handleRowLevelAct>

            </lightning-datatable>

        </template>
         <!-- Spinner -->
            <div if:true=showLoadingSpinner>
                <lightning-spinner alternative-text="Loading" size="large"></lightning-spinner>
            </div>


    </lightning-card>
</template>

RowLevelActionComp.js

import  LightningElement, track, wire  from 'lwc';
import PaymentDetails from '@salesforce/apex/ProductClass.getProductDetails';
import  ShowToastEvent  from 'lightning/platformShowToastEvent';
import  NavigationMixin  from 'lightning/navigation';
import  deleteRecord  from 'lightning/uiRecordApi';


//define row actions
const actions = [
     label: 'Show Details', name: 'view' ,
     label: 'Delete', name: 'delete'
 ];

const columns = [
    label: 'Product Name',fieldName: 'Name' , type: 'text', sortable: true ,
    label: 'Product Code',fieldName: 'ProductCode' , type: 'text', sortable: true ,
    label: 'Product Family',fieldName: 'Family' , type: 'picklist', sortable: true ,
    label: 'Active',fieldName: 'IsActive' , type: 'checkbox', sortable: true ,
    label: 'Description',fieldName: 'Description' , type: 'text', sortable: true ,

        type: 'action',
        typeAttributes:
            rowActions: actions,
            menuAlignment: 'right'



]

export default class RowLevelActionComp extends NavigationMixin (LightningElement) {
 columns = columns;
@track error;
@track data;
@track showLoadingSpinner = false;
refreshTable;

//retrieving the products using wire service...
@wire(PaymentDetails)
wiredProd(error, data)
    if(data)
        console.log('data is =>',data);
        this.data = data;
     else if(error)
        this.error = "No Products to show";



// Handle auto-number click event
handleRowLevelAct(event)
    const recordId = event.detail.row.Id
    const actionName = event.detail.action.name;



    switch (actionName)
        case 'view':
            this[NavigationMixin.Navigate](
                type: 'standard__recordPage',
                attributes:
                    recordId: recordId,
                    objectApiName: 'Product2',
                    actionName: 'view'

            );
            break;
        case 'delete':
            this.showLoadingSpinner = true;
            deleteRecord(recordId)
            .then(() =>
                this.showLoadingSpinner = false;
               this.dispatchEvent(
                   new ShowToastEvent(
                       title : 'Success',
                       message : 'Your Product has been deleted successfully' ,
                       variant : 'success'
                   )
               );
               return refreshApex(this.refreshTable);

            )
            .catch(error =>
                this.dispatchEvent(
                    new ShowToastEvent(
                        title : 'Error while deleting record',
                        message : error.body.message ,
                        variant : 'success'
                    )
                );

             );
             break;



}

RowLevelActionComp.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>58.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>

    </targets>
</LightningComponentBundle>

In the above example, in the controller, we retrieved all the product details from the Product object.

The retrieved data is displayed in a Lightning Datatable with columns for Product Name, Product Code, Product Family, Active, and Description respectively.

Here, deleteRecord, NavigationMixin, and ShowToastEvent are already imported according to requirements. The ‘Action’ column includes row-level actions for Show Details’, and ‘Delete’.

The handleRowLevelAct method is invoked when a row action is triggered. It checks the action name and performs the corresponding action.

Spinner in LWC:

We used a loading spinner in this Lightning Web component. As it is the best practice for improving user experience  nd indicating that a process is in progress.

Output:

In this lightning datatable, when the user clicks on the down arrow on the right side, the row-level action menu will be visible.

So, when the user clicks on “Show Details”, it will redirect the user to the product detail page/record page. And, when the user clicks on “Delete”, then that particular record will get deleted from the database.

Img1

In this way, we learnt how to handle row-level actions in Lightning Datatable in Lightning Web Component (LWC).