top of page
  • Writer's pictureA. Rawani

Quick actions using LWC component - Headless



Headless quick actions in Salesforce Lightning Web Components (LWC) is a powerful feature that revolutionizes how backend processes are managed. Unlike traditional UI-driven actions, headless quick actions operate seamlessly behind the scenes, executing tasks programmatically with a single click. This innovation not only enhances productivity by reducing manual steps but also empowers organizations to integrate complex workflows and external systems effortlessly. In this blog, we'll explore how to execute headless quick actions through a practical example.


What is LWC Quick action?

LWC Quick Actions provides a dynamic means of performing tasks within Salesforce with a minimum of clicks. Unlike traditional methods, which may involve navigating through multiple screens or tabs to achieve an objective, LWC Quick Actions provides a seamless experience straight from the user interface. Whether it's updating records, creating new entries, or triggering custom processes,  etc.


Types of Quick Action available in LWC


  1. Screen Action refers to a type of action that allows developers to create custom screens to collect and display information from users.

  2. Headless Actions refers to a Quick Action that is executed programmatically without a user interface (UI) component.Headless quick actions are initiated and executed behind the scenes, often as part of automated processes or integrations.



Sometimes we need to perform an action using quick action without showing the screen in which the logic needs to run in the backend. Headless Quick Action will help us to achieve that.


Let's take a use case where a user wants to restrict an account or customer. 


So, previously, the user had to go to edit the record and check the checkbox manually to restrict the account.


Now we can reduce the step and convert the whole process in a single button click using a headless quick action.


Now, let's dive into the implementation with the following code


Step-1. Create a LWC Component headlessAction


By implementing the below LWC component, we can configure the process that we need to perform by clicking the action button.


MetaFile : 

headlessAction.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>59.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordAction</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordAction">
          <actionType>Action</actionType>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

*In the above metafile we are using <targets>as an "lightning__RecordAction" which helps to Make the button to be placed on the record page and we are implementing


<targetConfigs>

  <targetConfig targets="lightning__RecordAction">

      <actionType>Action</actionType>

  </targetConfig>

</targetConfigs>

The above line of code helps to specify what type of quick action we want. Here we are using the action type as “Action” because we have to execute some process in the backend after clicking on a button.


HTMLFile : 

headlessAction.html
<template>  

</template>

*The html file will be empty in headless quick action.


JSFile : 

headlessAction.js
import {LightningElement, api, track} from 'lwc';

import {updateRecord} from 'lightning/uiRecordApi';

import RESTRICTED_FIELD from '@salesforce/schema/Account.Restricted__c';

import ID_FIELD from '@salesforce/schema/Account.Id';

import getAccountData from '@salesforce/apex/AccountController.getAccountRecord';

import {ShowToastEvent} from 'lightning/platformShowToastEvent';

export default class HeadlessAction extends LightningElement {

    @api recordId;

    //calling the invoke method

    @api invoke() {

        this.getAccountData();  

    }

    getAccountData(){

        getAccountData({recordId: this.recordId})

        .then((result) => {

            if(result.account.Restricted__c) {

                this.showToast('Info', 'Customer is already restricted', 'Info');

            }

            else {

                this.updateAccountRecord();

            }

        })

        .catch((error) =>{

            this.showToast('Error', 'Error while fetching the account data', 'Error');

        })

    }

    showToast(title, message, variant) {

        const event = new ShowToastEvent({

            title: title,

            message: message,

            variant: variant,

        });

        this.dispatchEvent(event);

    }

    updateAccountRecord() {

        const fields = {};

        fields[ID_FIELD.fieldApiName] = this.recordId;

        fields[RESTRICTED_FIELD.fieldApiName] = true;

        const recordInput = { fields };

        updateRecord(recordInput)

        .then(() => {

            this.showToast('Success', 'Customer is restricted', 'Success');

        })

        .catch((error) => {

            this.showToast('Error', 'Error while updating the record', 'Error');

        })

    }

}

*Calling invoke method is mandatory in headless quick action because on click of button invoke method gets executed first.


Step-2. Create 4 apex classes to handle the backend functionality


  1. AccountController

  2. AccountProcessor

  3. AccountWrapper

  4. AccountDomain.


Apex controller class :

public with sharing class AccountController {

   @AuraEnabled(cacheable=True)

    /**

    * This method aims to return Account record

    * @param String

    * @return AccountWrapper  

    */

    @AuraEnabled

   public static AccountWrapper getAccountRecord(String recordId) {

      return AccountProcessor.getProcessedRecord(recordId);

   }

}

Apex Processor Class :

public with sharing class AccountProcessor {

    /**

    * This method aims to get Account Record

    * @param : String recordId

    * @return : Account record

    */

    public static AccountWrapper getProcessedRecord(String recordId) {

        AccountWrapper processedAccountrecord;

       

        Account acc = AccountDomain.getAccountData(recordId);

        processedAccountrecord = new AccountWrapper(acc);

       

        return processedAccountrecord;

    }

}

Apex Wrapper Class : 

public with sharing class AccountWrapper {

    @AuraEnabled

    public Account account;

    public AccountWrapper(Account account) {

        this.account = account;

    }

}

Apex Domain Class : 

public class AccountDomain {   

    /**

    * This method aims to get Account record

    * @param String

    * @return Account

    */

    public static Account getAccountData(String recordId) {

        return [

            SELECT

                Id,

                Name,

                Restricted__c

            FROM

                Account

            WHERE

                Id =:recordId

        ];

    }

   }

Now configure the button on the Account page : 


Now add the button on the page layout


Now test it.


Conclusion 

In summary, Headless Quick Actions in LWC allow developers to create actions that run server-side logic without displaying a UI to the user. By using headless quick action we can reduce the process step by just clicking on one button we can perform the action. Lightning Headless Quick Actions provides a powerful mechanism for automating backend processes, improving efficiency, integrating systems, and enhancing overall user experience within Salesforce applications.


If you'd like to see the code and resources used in this project, you can access the repository on GitHub.To access the AVENOIRBLOGS repository, click here. Feel free to explore the code and use it as a reference for your projects.


Thank You! You can leave a comment to help me understand how the blog helped you. If you need further assistance, please contact us. You can click "Reach Us" on the website and share the issue with me.


Reference



Blog Credit:

A. Rawani

   Salesforce Developer

   Avenoir Technologies Pvt. Ltd.

  Reach us: team@avenoir.ai

Recent Posts

See All

Comments


bottom of page