Saturday, March 25, 2023

Call Approval Process on Button Click in Salesforce LWC

In some scenarios, we may need to call the standard approval process on click of a custom button. So in that case, we can have a lightning quick action in LWC similar to one in Aura components.

Step 1:

Create an action for an object. Lets say Opportunity. We need to specify the LWC component name. for create a LWC component and enter that name in Lightning Web Component field.

approval


Step 2:

Add that action in the required page layout in the section as shown below:

approval


So the configurations are done...


Step 3:

Let's do the code part

Open that already created LWC component and add this code.

LWC html file:

<template>
    <lightning-quick-action-panel header="Submit for Approval">
        <lightning-textarea label="Comments" value={commentsonchange={commentChange
                                class="textAreaBody">
        </lightning-textarea>
        <div slot="footer">
            <lightning-button variant="neutral" class="slds-m-left_x-small" label="Cancel" 
                                onclick={closeAction}>
            </lightning-button>
            <lightning-button variant="brand" class="slds-m-left_x-small" label="Submit" 
                                onclick={handleSubmitClick>
            </lightning-button>
        </div>
    </lightning-quick-action-panel>
</template>

------------------------------------------------

LWC Js file:

import { LightningElement,wire,track,api } from 'lwc';
import submitApproval from '@salesforce/apex/OppApproval.submitApproval';
import { CloseActionScreenEvent } from "lightning/actions";
import { CurrentPageReference } from 'lightning/navigation';

export default class OppApprovalLWC extends LightningElement {
@track comments;
@api recordId;

closeAction() {
    this.dispatchEvent(new CloseActionScreenEvent());
    }
@wire(CurrentPageReference)
    getStateParameters(currentPageReference) {
        if (currentPageReference) {
            this.recordId = currentPageReference.state.recordId;
        }
    }
commentChange(event) {
        this.comments = event.detail.value;
    }

handleSubmitClick(event){

        submitApproval({ oppId: this.recordId, comments: this.comments})
        .then(result =>{
            eval("$A.get('e.force:refreshView').fire();");
            this.dispatchEvent(new CloseActionScreenEvent());
        })
        .catch(error =>{
            
        });
        
    }
}

-------------------------------------------------

LWC Meta XML file:

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>54.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__RecordAction</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordAction">
        <actionType>ScreenAction</actionType>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>


-------------------------------------------------

Apex Class:


public class OppApproval {

 @auraEnabled

    public static void submitApproval(String oppId,String comments){
        try{
            Approval.ProcessSubmitRequest approvalRequest = new Approval.ProcessSubmitRequest();                
            approvalRequest.setObjectId(OppId);
            approvalRequest.setComments(comments);
     approvalRequest.setSkipEntryCriteria(true);
                Approval.ProcessResult approvalResult = Approval.process(approvalRequest);
                if(approvalResult .isSuccess()){
                    system.debug('success-'+approvalResult .isSuccess());
                }
                else{
                    system.debug('failed-'+approvalResult .isSuccess());
                }
            
        }
        catch (Exception e) {
            
            String errorMsg = e.getMessage();
            throw new AuraHandledException(ErrorMsg);
        }
        
    }
}

Salesforce Integration Design Patterns

Here are some of the integration patterns available in Salesforce:

1. Request-Reply: In this pattern, Salesforce sends a request to another system, and the other system responds with a reply. This pattern is useful when you need to get data from another system, or when you need to update data in another system.

2. Fire & Forget: Salesforce invokes a process in a remote system but doesn’t wait for completion of the process. Instead, the remote process receives and acknowledges the request and then hands off control back to Salesforce.

2. Batch Data Synchronization: In this pattern, data is exchanged between two systems periodically in batches. This is useful when large volumes of data need to be transferred between systems.

3. Data Virtualization: Salesforce accesses external data in real time. This removes the need to persist data in Salesforce and then reconcile the data between Salesforce and the external system

4. Middleware Integration: This pattern involves using middleware such as MuleSoft or Dell Boomi to connect systems. Middleware can help to manage the complexity of integrations by providing features such as data transformation, routing, and error handling.

5. Point-to-Point: This pattern is used when you need to connect Salesforce with a single system. Point-to-point integration can be simple to set up and maintain, but it can become complex if you need to connect Salesforce with multiple systems. 

Overall, the integration pattern you choose will depend on the complexity of the integration, the volume of data being transferred, and the real-time requirements of your business processes.

These patterns can be used individually or in combination to create a comprehensive integration strategy for your organization. The choice of pattern will depend on the specific requirements of your integration project.


Let me know your thoughts in the comment section!!

Sunday, March 19, 2023

What are Named Credentials in Salesforce? What are its Benefits

Let us understand what are Named Credentials in Salesforce and what are its Benefits

Using Named Credential, we can make call out to external system without supplying username or Password
A named credential specifies the URL of a callout endpoint and its required authentication parameters in one definition. To simplify the setup of authenticated callouts, specify a named credential as the callout endpoint.

Why Avoid Hardcoding Credentials :

  1. It is a Maintenance nightmare. Having Credentials hardcoded means you have to deploy the changes every single time like when your password changes or expires.
  2. It is also difficult to maintain changes in a different environment
  3. Not very secure.

Benefits of using Named Credentials :

  1. Authentication is done by Salesforce and you need not to worry about that.
  2. Easy for admins to maintain.
  3. Secure storage of credentials.
  4. No need to create a Remote Site Setting if using a Named Credential.
  5. The callout is easier to maintain. No hard coding involved.

Apex HTTP Callout Without Named Credential:

HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setEndpoint('https://example .com/path/my/api');
String username = 'username';
String password = 'password';
//Add basic authentication header to the callout
Blob headerValue = Blob.valueOf(username + ':' + password);
String authHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authHeader);
Http h = new Http();
HttpResponse response = h.send(req);
System.debug('response-'+ response);

Apex HTTP Callout With Named Credential:

HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setEndpoint('callout:Sample_API/some_path');
//No need to manually set any headers here. Salesforce will add this for us automatically.
Http http = new Http();
HTTPResponse response = http.send(req);
System.debug('response-'+ response);

Saturday, March 18, 2023

What is Master Label Tag in LWC Meta File

Master label is a custom name given to a lightning web component. Developers can given user-friendly name and that name will be visible in the Lightning App Builder and in Experience Builder.

Sample meta.xml code-

<apiVersion>42.0</apiVersion>
<isExposed>true</isExposed>
<masterLabel>MyLWCComponent</masterLabel>
<targets>
    <target>lightning__RecordPage</target>
    <target>lightning__AppPage</target>
    <target>lightning__HomePage</target>
</targets>


So next time when you add a lightning component in a page, search Master Label(MyLWCComponent) in App builder.

Let me know your thoughts in the comment section!!

Friday, March 17, 2023

With sharing & Without sharing keywords in APEX

With sharing & Without sharing keywords in APEX


With sharing Keyword:

This keyword enforces sharing rules that apply to the current user. If absent, code is run under default system context. Use the with sharing keywords when declaring a class to enforce the sharing rules that apply to the current user. Use With Sharing when the User has access to the records being updated via Role, Sharing Rules, Sales Teams – any sort of sharing really.

Example:

public with sharing class sharingClass {

// Code here

}

Without sharing keyword:

Ensures that the sharing rules of the current user are not enforced. Use the without sharing keywords when declaring a class to ensure that the sharing rules for the current user are not enforced. For example, you may want to explicitly turn off sharing rule enforcement when a class acquires sharing rules when it is called from another class that is declared using with sharing. Without Sharing is reserved for cases where the User does not have access to the records, but there is a need to update them based on user input.

public without sharing class noSharing {

// Code here

}

Some things to note about sharing keywords:

  • The sharing setting of the class where the method is defined is applied, not of the class where the method is called. For example, if a method is defined in a class declared with with sharing is called by a class declared with without sharing, the method will execute with sharing rules enforced.
  • If a class isn’t declared as either with or without sharing, the current sharing rules remain in effect. This means that the class doesn’t enforce sharing rules except if it acquires sharing rules from another class. For example, if the class is called by another class that has sharing enforced, then sharing is enforced for the called class.
  • Both inner classes and outer classes can be declared as with sharing. The sharing setting applies to all code contained in the class, including initialization code, constructors, and methods.
  • Inner classes do not inherit the sharing setting from their container class.
  • Classes inherit this setting from a parent class when one class extends or implements another.

Please share the blog and leave a comment about your thoughts.
Click here for more blogs.

Mostly Viewed