Saturday, March 25, 2023

How to Query Salesforce Objects from External System Without Code

Sometimes, external system wants to get the latest data from Salesforce to run the business logic in their system. In those cases, external system can do a simple query Salesforce objects with the help of Salesforce Standard APIs. There is no code required from a Salesforce developer

Lets understand this concept with an example.

Consider Workbench as a external system. To query salesforce objects in workbench we need to follow the below pattern:

 /services/data/v20.0/query?q=SELECT+Id+,+Name+FROM+USER

where every element is concatenated by + operator

After the query is added click on Execute and once the response comes then click on Show Raw Data. It will open up the blue screen on the right.

workbench


  • totalsize attribute is the number of records returned.
  • At a time workbench can display 2000 records under raw response.
  • If the number of records returned are more than 2000 then NextRecordsUrl will be used to get next set of 2000 records.
  • Done Attribute under raw response tells whether we have reached the last page or not. 
  • If done = false then we need to NextRecordUrl to get next records.
  • If done = false, that mean there are no more records after this.

We can also write where clause in the query
SELECT+Id+,+Name+FROM+USER+where+id+=+'+00500xx+'
Similarly, we can add any filter in the query and get back the response.


Let me know your thoughts on this and we can discuss more.

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!!

Mostly Viewed