How to Add Buttons in Salesforce LWC Datatable?

In the Salesforce LWC data table, we can add action buttons to view, edit, or delete a record from the data table. In this Salesforce tutorial, we will learn how to add action buttons in the Salesforce LWC data table for each row.

Add buttons in the Salesforce LWC data table

To create a Salesforce LWC data table with action buttons, follow the steps below.

  1. First, we will create a controller class to fetch the object records. In this example, I will fetch the Contact object records.

Enter the code below for the contact controller class.

public with sharing class ContactController {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getContacts() {
        return [SELECT Id, FirstName, LastName, Email FROM Contact LIMIT 10];
    }
}
  1. Create an LWC component and enter the code below for the HTML file.
<template>
    <lightning-card title="Contacts with Actions" icon-name="standard:contact">
        <template if:true={contacts}>
            <lightning-datatable key-field="Id" data={contacts} columns={columns} hide-checkbox-column="true"
                show-row-number-column="true" onrowaction={handleRowAction}>
            </lightning-datatable>
        </template>
    </lightning-card>
</template>

In the above code, we have used the onrowaction={handleRowAction} attribute that calls the handleRowAction function from the JS file when an action button is clicked.

  1. After this, enter the code below in the LWC component’s JS file that will handle the logic to display the button in the Lightning Data Table.
import { LightningElement, track, wire } from 'lwc';
import fetchContacts from '@salesforce/apex/ContactController.fetchContacts';
import { NavigationMixin } from 'lightning/navigation';
import { deleteRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

const COLUMNS = [
    { label: 'Name', fieldName: 'Name' },
    { label: 'Phone', fieldName: 'Phone' },
    { label: 'Email', fieldName: 'Email' },
    { label: 'Title', fieldName: 'Title' },
    {   type: 'button', label: 'Actions', initialWidth: 250, typeAttributes: {
            label: 'View', name: 'View', title: 'View', iconName: 'utility:preview', variant: 'Brand'
        }
    },
    {   type: 'button', typeAttributes: {
            label: 'Edit', name: 'Edit', title: 'Edit', iconName: 'utility:edit', variant: 'Brand'
        }
    },
    {   type: 'button', typeAttributes: {
            label: 'Delete', name: 'Delete', title: 'Delete', iconName: 'utility:delete', variant: 'destructive'
        }
    }
];

export default class ContactTable extends NavigationMixin(LightningElement) {
    @track contacts;
    columns = COLUMNS;

    @wire(fetchContacts)
    wiredContacts({ data, error }) {
        if (data) {
            this.contacts = data;
        }
    }

    handleRowAction(event) {
        const actionName = event.detail.action.name;
        const recordId = event.detail.row.Id;

        if (actionName === 'View' || actionName === 'Edit') {
            this[NavigationMixin.Navigate]({
                type: 'standard__recordPage',
                attributes: {
                    recordId: recordId,
                    objectApiName: 'Contact',
                    actionName: actionName.toLowerCase()
                }
            });
        } else if (actionName === 'Delete') {
            deleteRecord(recordId)
                .then(() => {
                    this.dispatchEvent(new ShowToastEvent({
                        title: 'Success',
                        message: 'Record deleted successfully',
                        variant: 'success'
                    }));
                });
        }
    }
}

In the above code, using the @wire method, we have fetched the contact data in the table with action buttons for viewing, editing, and deleting each contact from the row.

We have used the NavigationMixin function to navigate to the view or edit page of the record when the user clicks on the view or edit button.

When a user clicks an action button, the handleRowAction(event) method gets the selected action and the row data. The action name (view, edit, or delete) is extracted from event.detail.action.name, and the row details are taken from event.detail.row.

Based on the selected action, the method calls the corresponding function (viewRecord, editRecord, or deleteRecord).

The Showtoastevent is a standard event to show the pop-up message of successful deletion after deleting the record.

  1. Make the component visible to the lightning pages using the below code in the meta.xml file inside the <LightningComponentBundle> tag.
isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
  1. Now, navigate to the Lightning App page to deploy the LWC component.

Click on the settings icon and select Edit page, and in the app builder, drag and drop the LWC component to the Lightning page and save the changes.

After this, we will see the LWC data table with action buttons Edit, View, and Delete in each row.

Add action buttons to rows in LWC data table

This way, we can add buttons to the Salesforce LWC lightning data table by following the above steps.

Conclusion

In this Salesforce tutorial, we have learned how we can add custom button actions in Salesforce Lightning data tables, such as View, Edit, and Delete. In the above steps, we created an LWC table and displayed data fetched from the Apex class. The row actions were then managed through the NavigationMixin for navigation and the deleteRecord method for deletions.

By following the above steps, you will be able to implement the action button efficiently in the rows of the Salesforce LWC data tables.

You may also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.