Tuesday, September 22, 2020

Different ways of calling Apex Class from Lightning Web Component

 

To call apex from Lightning Web Component, you need to import the apex method in JavaScript class.

There are three ways by which we can call an apex from LWC-

·       Wire a property

·       Wire a function

·       Call apex imperatively

The syntax of importing apex class in JavaScript is like-

import apexMethodName from ‘@salesforce/apex/Namespace.ClassName.apexMethodName’;

@AuraEnabled annotation must be use to expose an apex class to LWC. The apex method must be static global/public

Wire a Property:

The apex class must be declared with @AuraEnabled(cacheable=true) when using wire service to call apex. Making a method cacheable improved the component performance by showing the client side cached data instead of invoking server side controller.

 

Scenario: calling apex method without parameter

In this scenario, the syntax to call apex is

@wire (<METHOD_NAME>)<WIRE_PROPERTY>

@wire indicates that you are using wire service to call Apex and to call the method before you use @wire decorator, import the method like-

import getAccountList from '@salesforce/apex/AccountSearchLwcController.getAccountList';

WIRE_PROPERTY is the private property of the component which received the returned result of the wire service. There are two properties within the wire property. The data property stores the returned result and error property return in case any error.


import { LightningElement,wire} from 'lwc';
import getAccountList from '@salesforce/apex/AccountSearchLwcController.getAccountList';
export default class AccountSearchLwc extends LightningElement {
    @wire(getAccountList)
    accounts;
}

Apex Class:

public with sharing class AccountSearchLwcController {
    @AuraEnabled(cacheable=true)    
    public static List<Account> getAccountList() {
    string queryStr = 'select id,name,Phone,Email__c, Accountnumber from Account';
        List<Account> listofAccounts =Database.query(queryStr);
        
        return listofAccounts;
    }

html:

<template>
    <div class="slds-var-m-around_medium">
        <template if:true={accounts.data}>
            <template for:each={accounts.data} for:item="account">
                <p key={account.Id}>{account.Name}</p>
            </template>
        </template>
        <template if:true={accounts.error}>
            <p>SOME ERROR OCCURS </p>
        </template>
    </div>
</template>

Scenario: Call apex with parameter

Here the apex method takes an input and returned the list of account where account name contains the input parameter.

To call the apex method with parameter using @wire service, the syntax is:

@wire(<METHOD_NAME>,{<Apex_Class_Paramerter>:<INPUT_PARAMETER_FROM_LWC>})

<WIRE_PROPERTY>

Here we need to use ‘$’ symbol with the JavaScript parameter to indicate that its dynamic and reactive which means if value of the searchKey parameter changes in LWC then the template will be rendered in html.

import { LightningElement,wire} from 'lwc';
import getAccountList from '@salesforce/apex/AccountSearchLwcController.getAccountList';
export default class AccountSearchLwc extends LightningElement {
    searchKey='Josh';
    @wire(getAccountList,{searchKey:'$searchKey'})
    accounts;
}

APEX Class:

public with sharing class AccountSearchLwcController {
    @AuraEnabled(cacheable=true)    
    public static List<Account> getAccountList(String searchKey) {
        string searchStr = '';
        if (searchKey!='') {
            searchStr = ' where name LIKE \'%'+searchKey+'%\'';
        }
        string queryStr = 'select id,name,Phone,Email__c, Accountnumber from Account';
        queryStr = queryStr+searchStr;
        List<Account> listofAccounts =Database.query(queryStr);
        
        return listofAccounts;
    }
}

Wire a function:

Use wire a function when you want to operate on return data. This @wire service as function retuned the result as an object with either data property or error property. If data property is there then it is assigned to this.accounts and for error it is assigned to this.error. If the value of this property changes, then the template rerenders.


import { LightningElement,track,wire} from 'lwc';
import getAccountList from '@salesforce/apex/AccountSearchLwcController.getAccountList';
export default class AccountSearchLwc extends LightningElement {
    searchKey='Josh';
    accounts;
    error;
    @wire(getAccountList,{searchKey:'$searchKey'})
    Wiredaccounts({error,data}){
If(data){
            this.accounts= data;
 	     this.error = undefined;
}else if(error){
      this.error = error;
      this.data = undefined;
}	
    }
}

Call Apex Imperatively:

Apex needs to call imperatively when you need to control when the invocation needs to be there for example, on-change event or button click event. Here in this example, the getListOppty() JS method gets  called on click of a button which in turn call the getOpptyList() apex method and return list of opportunity.

import { LightningElement,track,wire} from 'lwc';
import getAccountList from '@salesforce/apex/AccountSearchLwcController.getAccountList';

export default class AccountSearchLwc extends LightningElement {
    opptyList;
    error;
    
    getListOfOppty(){
        getOpptyList() //getOpptyList() is the apex Method Name
        .then(result=>{
            this.opptyList = result;
            this.error = undefined;
        })
        .catch(error=>{
            this.opptyList = undefined;
            this.error = error;
        });      
    }
}

Thursday, September 17, 2020

Integrating two Salesforce Org Using Named Credential



Security is the one which every customer concern about while implementing SF application and integrating with external system. So if we want to hide the external url, username, password while connecting external system, then Named Credential is something that you need to implement.

Named credential specifies the call out end point url and authentication in one definition. It doesn’t require to add end point URL in Remote Site settings. Named credential support two types of authentication protocol Basic User Name/Password Authentication and OAuth 2.0 protocol.

In this blog article, we will be going to connect two salesforce Org using Named Credential and OAuth 2.0 authentication protocol.

Following steps, we need to perform –

Steps#1: Create connected App in destination org

Steps#2: Create AuthProvider in source Org

Steps#3: Create named Credential in source Org

Steps#4: Write apex in source Org to fetch data from destination Org.

 

Connected App in destination Org:

A connected app is a framework that enables an external application to integrate with Salesforce using different authentication protocol. Please check salesforce article about Connected App

 

Go to SetupàCreateàAppsà New (Connected App)

Checked Enable OAuth Settings and select the OAuth scope. OAuth scope is basically the level access that connected App needed for the integration.



Put callback url as dummy url which we will change later.

 

Create Auth Provider in Source Org:

Go to SetupàSecurity Controls à Auth. Provider à New



Copy the Consumer Key/Consumer Secret of the connected app created in destination org.

The Authorization end point should be -

https://<base url of the destination org>/services/oauth2/authorize

and Token Endpoint Url should be-

https://<base url of the destination org>/services/oauth2/token

Default Scope is the permission scope which need to be enter. There should be a space between two scope.

Upon clicks on save, it will generate call back url-

Copy the call back url and paste the same in the connected App in destination Org.


Named Credentials in source Org:

Go to SetupàSecurity Controls à Named Credentials à New Name Credential

Select Authentication Protocol as OAuth 2.0 and choose Authentication Provider which has been created in earlier steps. On clicks on save the page will redirect to destination Org where you need to login to verify the authentication.

 



Write Apex to connect destination org and fetch data:

Now calling an external system is only 5-6 lines code. No user name, No password, No end point URL. You only need to specify the named credential name which will take care the authentication.

Set httpsRequest endpoint as-

callout:<NAMED_CREDENTIAL>/<SOME_PATH>