Calling Apex method from a Quick Action in Salesforce Lightning using Aura component

Calling Apex method from a Quick Action in Salesforce Lightning using Aura component

Using aura:handler name = “init”, we an invokeApex method from a Quick Action in Salesforce Lightning using Aura component. From the action attribute, call the JavaScript function. In the JavaScript function, call the apex method. Check the following example with sample code reference.

Sample Code:

Apex Class:

public class AccountController {
    
    @AuraEnabled  
    public static void updateAccount( String recId ) {
        
        update new Account( Id = recId, Description = String.valueOf( System.now() ) );
        
    }
    
}

Aura Component:

<aura:component implements="force:hasRecordId,force:lightningQuickAction" controller="AccountController">
    <aura:handler name = "init" value = "{!this}" action = "{!c.onInit}"/>
</aura:component>

JavaScript Controller:

({  
    
    onInit : function( component, event, helper ) {    
        
        let action = component.get( "c.updateAccount" );  
        action.setParams({  
            recId: component.get( "v.recordId" )
        });  
        action.setCallback(this, function(response) {  
            let state = response.getState();  
            if ( state === "SUCCESS" ) {  
                
                $A.get("e.force:closeQuickAction").fire();  
                $A.get('e.force:refreshView').fire();   
                
            }  else {
                
                let showToast = $A.get( "e.force:showToast" );
                showToast.setParams({
                    title : 'Testing Toast!!!',
                    message : 'Record Not Saved due to error.' ,
                    type : 'error',
                    mode : 'sticky',
                    message : 'Some error occured'
                });
                showToast.fire();
                
            }
        });  
        $A.enqueueAction( action );         
        
    }
    
})

Quick Action:

Page layout configuration:

The Quick Action should be added to the “Salesforce Mobile and Lightning Experience Actions” section in the page layout.

Output:

Leave a Reply