Deep Clone using Headless Actions in LWC

A headless quick action executes custom code in a Lightning web component. Unlike a screen action, a headless action doesn’t open a modal window. So in short, if you want to do some custom logic via apex to run by click of a quick action button we can use headless actions in LWC.

Below are a few examples/use cases where we can implement headless actions.
1. A custom clone button (With Deep Clone)
2. A custom approval button.
3. Submit data to an external system.
4. Enrich the record with details from an external system etc.

Configure a Component for Quick Actions

To use a Lightning web component as a quick action, define the component’s metadata. Specifically to use an LWC as headless action use the below XML for the meta XML file. Note that the <actiontype is Action for a headless quick action and if you would like to enable the component as a screen popup (regular) include actionType as ScreenAction.

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

Implementation

Now that we have the setup ready, the custom logic that you need to implement must be provided with the js file of the LWC. The HTML file could be empty with just the template tags.
In your Lightning web component, expose invoke() as a public method. The invoke() method executes every time the quick action is triggered.

import { LightningElement, api } from "lwc";

export default class HeadlessSimple extends LightningElement {
  @api invoke() {
    console.log("This is a headless action.");
  }
}

Example Scenario

So now if you want to use a deep clone logic from the quick action button the code looks like this.

import { LightningElement, api } from "lwc";
import { ShowToastEvent } from 'lightning/platformShowToastEvent'
import { NavigationMixin } from 'lightning/navigation';
import startDeepClone from '@salesforce/apex/ROR_CloneController.startDeepClone';

export default class Ror_deepcloneaction extends NavigationMixin(LightningElement) {

    @api invoke() {
        this.startToast('Deep Clone!','Starting cloning process...');
        //Call the cloning imperative apex js method
        this.startCloning();
    }
    
    startCloning(){
        startDeepClone({recordId: this.recordId})
        .then(result => {
            this.startToast('Deep Clone!','Cloning Process Completed');
            this.navigateToRecord(result);
         })
         .catch(error => {
            this.startToast('Deep Clone!','An Error occured during cloning'+error);
         });
    }

    startToast(title,msg){
        let event = new ShowToastEvent({
            title: title,
            message: msg,
        });
        this.dispatchEvent(event);
    }

    navigateToRecord(clonedRecId){
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: clonedRecId,
                actionName: 'view',
            },
        });
    }

}

You can see that on click of the quick action button, the invoke method gets executed, that in turn calls the imperative apex call; does the clone; returns the new clone record’s id and on a successful return from the apex, use an event to alert the user and use NavigationMixin to redirect the user to the cloned record.

Please access the code from the Github repo here.

Aura’s Helper Equivalent in LWC

Back in time when we were creating Lightning components on aura framework, developers were hooked on with the helper methods. We all were told that all the reusable code should go into helper methods. However when we moved to LWC development, with no helper javscript file, where do we put all these reusable code? Let is take a look.

Reusable helpers in LWC

In LWC, we just have one javascript file, so it is necessary to have all the reusable code written within this file. Lets take a quick example of how we can call a method that fires toast message. This method we’ll make generic and try to refer from multiple places. Also I’ve added how to use a pattern matching method as well.

import { LightningElement} from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class MyClass extends LightningElement {
    searchTerm = null;
    //Function for maanging toast messages
    showToast(titleMsg,description,variant) {
        const event = new ShowToastEvent({
            title: titleMsg,
            message: description,
            variant : variant
        });
        this.dispatchEvent(event);
    }
    checkNumeric(inputStr){
        let pattern = /^([^0-9]*)$/;
        if(!inputStr.match(pattern)){
            return true;
        }
        else {
            return false;
        }
    }
    validateParam(searchTerm) {
        let searchTermLen = searchTerm.length;
        if (searchTermLen === 0 || searchTermLen > 3) {
            this.showToast('Error','Search Term from must have minimum 1 and maximum 3 characters', 'error');
        }
        else if (searchTermLen === 1) {
            if(this.checkNumeric(searchTerm)){
                //Some Logic
            }
            else {
                this.showToast('Error','First Character of Search starts with Number', 'error');
            }
        }
    }
    //The handler that will executed from the click of search button
    handleSearchClick(event) {
        this.validateParam(this.searchTerm);
            // Do all your logic below
        }
}

From the above its evident that on handleSearchClick(), we call the validateParam() method. From the validateParam() method we are calling the showToast() method by passing parameters. The showToast() method based on its input parameter will render the toast message on the UI.

‘This’ – The magic word!

The key to call reusable code is the use of ‘this‘ keyword. Functions, in JavaScript, are essentially objects. Like objects they can be assigned to variables, passed to other functions and returned from functions. And much like objects, they have their own properties. One of these properties is ‘this‘.

The value that ‘this‘ stores is the current execution context of the JavaScript program. Thus, when used inside a function this‘s value will change depending on how that function is defined, how it is invoked and the default execution context.

Blog at WordPress.com.

Up ↑