Custom Approval Button In Salesforce Lightning

Hey Awesome Readers! I hope, you’re happy and safe.

Hope we all aware of the Standard Approval Process or flow. In basic terms, if we can describe the Approval process as it’s an automated process which is using in salesforce organization for approval of records. This terma Approval defined because it requires some steps to be approved by persons. So, in today’s post let’s learn together how to create a custom approval button by passing the recordId as a parameter, and then you can create the Lightning button in the component.

This article explains the Automatic submission of the Approval process using the Apex and lightning component. It includes Automatic submission, approval steps as well as the rejection of record completely using apex and component and how to handle the error and success message.

Usage of this article:

  1. Click on the custom button submit the record for approval on the basis of the field value.
  2. We will handle the Approve / Reject the record on the basis of the field and then will show the success and error message.

Create the Apex Class:

public class SubmitForApprovalGen {
    @auraEnabled
    public static string submitAndProcessApprovalRequest(String recordId, String comment) {
        string response;
        Id Userid=UserInfo.getUserId();
        try{
            recordId = String.escapeSingleQuotes(recordId);
            comment = String.escapeSingleQuotes(comment);
            Id idToProccess = recordId;
            Schema.sObjectType entityType = idToProccess.getSObjectType();
            system.debug('entityType:::'+entityType);
            String entity = String.valueOf(entityType);
            List<ProcessDefinition> appProcessName = new List<ProcessDefinition>([SELECT Id,Name,TableEnumOrId,State,DeveloperName from ProcessDefinition where TableEnumOrId=: entity and State='Active']);
            
            if(appProcessName.isEmpty()){
                response = 'failure';
            }
            else{
                Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
                if(string.isNotBlank(comment) && comment != null)
                {
                    req1.setComments(comment);
                }
                req1.setObjectId(recordId);
                req1.setSubmitterId(Userid); 
                req1.setProcessDefinitionNameOrId(appProcessName[0].DeveloperName);
                Approval.ProcessResult result = Approval.process(req1);
                response = 'success';
            }
        }
        catch(System.DmlException ex){
            system.debug('Error Message ::: ' + Ex.getMessage() + ' Due to this issues ::: ' + Ex.getLineNumber());   
            response = Ex.getMessage(); 
        }
        return response;
    }
    @auraEnabled
    public static string approvalProcessStatus(String recordId) {
        string response;
        recordId = String.escapeSingleQuotes(recordId);
        //Taking out already running Approval Process.
        List<ProcessInstance> appProcessList = [Select Id, Status From ProcessInstance WHERE TargetObjectId =: recordId LIMIT 1];
        if(appProcessList.size()==0){
            response = 'success';
        }
        else{
            response = 'failure';
        }
        system.debug('response::'+response);
        return response;
    }
}

Now, Create customapp.cmp

<aura:component controller="SubmitForApprovalGen" 
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" 
                access="global" >
    <aura:attribute name="recordId" type="Id" />
    <aura:attribute name="comment" type="String" default="" />
    <aura:attribute name="loaded" type="Boolean" default="true" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <aura:html tag="style">
        .modal-footer, .THIS .slds-modal__footer {
        display: none;
        }
    </aura:html> 
    <div class="inputArea">
        <lightning:textarea name="comment" label="Comments" value="{!v.comment}" placeholder="type here..." />
    </div>
    
    <div class="Holder">
        <div class="slds-text-align_center slds-p-top_small">
            <aura:if isTrue="{! v.loaded }">
                <lightning:button variant="brand" label="Submit" onclick="{!c.handleClick}" />
                <aura:set attribute="else">
                    <lightning:spinner alternativeText="Loading..." />
                </aura:set>
            </aura:if>
        </div>
    </div>
</aura:component>

Now, Create customappController.js

({
    doInit : function(component, event, helper) {
        helper.approvalStatusChecker(component, event, helper);
    },
    handleClick : function (component, event, helper) {
        helper.goToSubmitApproval(component, event, helper);
    }
})

Now, Create customappHelper.js

({
	approvalStatusChecker : function(component, event, helper){
        var getID = component.get("v.recordId");
        var action = component.get('c.approvalProcessStatus');
        action.setParams({"recordId": component.get("v.recordId")});
        action.setCallback(this, function(response) {
            var state = response.getState();
            console.log('state::'+state);
            if(state === "SUCCESS") {
                var resp = response.getReturnValue();
                if(resp == 'failure'){
                    console.log('response:::'+resp);
                    helper.showToast(component, event, helper, 'error', 'This record is already submitted','Error Message');
                    $A.get("e.force:closeQuickAction").fire(); 
                }   
            } else {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " +
                                    errors[0].message);
                    }
                } else {
                    console.log("Unknown error");
                }
                console.log('Problem getting account, response state: ' + state);
            }
        });
        $A.enqueueAction(action);        
    },
    goToSubmitApproval : function(component, event, helper){
        component.set('v.loaded', false);
        var getID = component.get("v.recordId");
        //console.log('Id:::'+getID);
        var getComment = component.get("v.comment");
        //alert('comments:::'+getComment);
        var action = component.get('c.submitAndProcessApprovalRequest');
        action.setParams({"recordId": component.get("v.recordId"), "comment": component.get("v.comment")});//need modification
        
        // Configure response handler
        
        console.log('action::'+JSON.stringify(action));
        action.setCallback(this, function(response) {
            var state = response.getState();
            if(state === "SUCCESS") {
                
                var resp = response.getReturnValue();
                console.log('response:::'+resp);
                if(!$A.util.isEmpty(resp) && resp == 'success') {
                    helper.showToast(component, event, helper, 'success', 'Your approval process successfully submitted!', 'Success Message');
                    $A.get("e.force:closeQuickAction").fire();
                    $A.get('e.force:refreshView').fire();
                }
                if((!$A.util.isEmpty(resp)) && (!$A.util.isUndefined(resp)) && resp.includes('first error:')) {
                    var showErrorList = [];
                    showErrorList = resp.split('first error: ');
                    helper.showToast(component, event, helper, 'error', showErrorList[1], 'Error Message');
                    var erromessage = showErrorList[1];
                    console.log('erromessage==='+erromessage);
                    $A.get("e.force:closeQuickAction").fire();
                }
                if(resp == 'failure'){
                    helper.showToast(component, event, helper, 'error', 'No Active Approval Process Found.','Error Message');
                    $A.get("e.force:closeQuickAction").fire();                    
                }
                component.set('v.loaded', false);
            } else {
                component.set('v.loaded', true);
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " +
                                    errors[0].message);     
                    }
                } else {
                    console.log("Unknown error");
                }
                console.log('Problem getting account, response state: ' + state);
            }
        });
        $A.enqueueAction(action);
    }, 
    
    showToast : function(c, e, h, messageType, message, title) {
        var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            title : title,
            message: message,
            messageTemplate: '',
            duration:' 10000',
            key: 'info_alt',
            type: messageType,
            mode: 'dismissible'
        });
        toastEvent.fire();
    }
})

Let me know in the comment section if this component helps you out or if you thinks to additional functionality. !!

You can Chat with us, We will be more than happy to assist you.

And Thank you for being an awesome readers!

Popular Post:

You may also like...