May 28, 2020

Subscribe, Unsubscribe MessageChannel in LWC, Aura and Visualforce Page in Salesforce

GitHub Source Code:

SampleChannel.messageChannel-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
    <masterLabel>SampleChannel</masterLabel>
    <isExposed>true</isExposed>
    <description>This is a sample Lightning Message Channel.</description>
    <lightningMessageFields>
        <fieldName>variable1</fieldName>
        <description>Variable 1</description>
    </lightningMessageFields>
    <lightningMessageFields>
        <fieldName>variable2</fieldName>
        <description>Variable 2</description>
    </lightningMessageFields>
</LightningMessageChannel>


Aura:

Component:

<aura:component implements="flexipage:availableForAllPageTypes" access="global">
   
    <aura:attribute type="String" name="ReceivedMessage"/>
   
    <lightning:messageChannel onMessage="{!c.onMessageReceive}"
                              scope="APPLICATION"
                              type="SampleChannel__c"
                              aura:id="sampleMessageChannel"/>
   
    <div class="slds-box slds-theme--default">
       
        <lightning:button label="Publish" onclick="{! c.publish }"/><br/><br/>
           
        Message Received is {! v.ReceivedMessage }
           
    </div>

</aura:component>


Component JavaScript:

({
   
    onMessageReceive : function( component, message, helper ) {
       
        if ( message != null )
            component.set( "v.ReceivedMessage",
                          ( message.getParam( "variable1" ) + " - " + message.getParam( "variable2" ) ) );

    },
   
    publish: function( component, event, helper ) {
        var payload = {
            variable1: "Sample",
            variable2: "From Aura Component"
        };

        component.find( "sampleMessageChannel" ).publish( payload );
       
    }
   
})


LWC:

HTML:

<template>
    <lightning-card title="Publishing from LWC" icon-name="custom:custom14">
        <div class="slds-m-around_medium">
            <lightning-button label="Subscribe" onclick={subscribeMC}></lightning-button><br/><br/>
            <lightning-button label="Unsubscribe" onclick={unsubscribeMC}></lightning-button><br/><br/>
            <lightning-button label="Publish" onclick={handleClick}></lightning-button><br/><br/>
            Message Received is {receivedMessage}
        </div>
    </lightning-card>
</template>


JavaScript:

import { LightningElement, wire } from 'lwc';
import { subscribe, publish, MessageContext, APPLICATION_SCOPE } from 'lightning/messageService';
import SAMPLEMC from "@salesforce/messageChannel/SampleChannel__c";

export default class MessageChannelLWC extends LightningElement {

    @wire(MessageContext)
    messageContext;
    receivedMessage;
    subscription = null;

    handleClick() {

        const message = {
            variable1: "Test",
            variable2: "From LWC"
        };
        publish( this.messageContext, SAMPLEMC, message);

    }

    subscribeMC() {

        if (this.subscription) {
            return;
        }
        this.subscription = subscribe(
            this.messageContext,
            SAMPLEMC, ( message ) => {
                this.handleMessage( message );
            },
            {scope: APPLICATION_SCOPE});

    }

    unsubscribeMC() {

        unsubscribe( this.subscription );
        this.subscription = null;

    }

    handleMessage( message ) {

        this.receivedMessage = message ? JSON.stringify( message, null, '\t' ) : 'no message payload';

    }

}


JavaScript-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>


Visualforce Page:

<apex:page >
   
    <div>
       
        <p>Subscribe to SampleChannel</p>
        <button onclick="subscribeMC()">Subscribe</button>
        <p>Unsubscribe from SampleChannel</p>
        <button onclick="unsubscribeMC()">Unsubscribe</button>
        <br/>
        <br/>
        <button onclick="publishMC()">Publish</button>
        <br/>
        <br/>
        <p>Received message:</p>
        <textarea id="MCMessageTextArea" rows="10" style="disabled:true;resize:none;width:100%;"/>
       
    </div>
    <script>
   
        // Load the MessageChannel token in a variable
        var SAMPLEMC = "{!$MessageChannel.SampleChannel__c}";
        var subscriptionToMC;
        // Display message in the textarea field
        function onMCPublished(message) {
           
            console.log( 'Message is ' + JSON.stringify( message ) );
            var textArea = document.querySelector("#MCMessageTextArea");
            textArea.innerHTML = message ? JSON.stringify(message, null, '\t') : 'no message payload';
           
        }

        function subscribeMC() {
           
            if ( !subscriptionToMC ) {
               
                subscriptionToMC = sforce.one.subscribe( SAMPLEMC, onMCPublished, {scope: "APPLICATION"} );
                console.log( 'Subscription is ' + JSON.stringify( subscriptionToMC ) );
               
            }
           
        }

        function unsubscribeMC() {
           
            if ( subscriptionToMC ) {
               
                sforce.one.unsubscribe( subscriptionToMC );
                subscriptionToMC = null;
               
            }
           
        }
   
        function publishMC() {
       
            const message = {
                variable1: "Example",
                variable2: "From Visualforce Page"
            }
            sforce.one.publish( SAMPLEMC, message );
       
        }
   
    </script>

</apex:page>


Output:




How to create a MessageChannel in Salesforce using VS Code?

To create a MessageChannel, use the below steps

1. Open VS Code.

2. Create a Folder with the name "messageChannels" under force-app\main\default.


3. Create a file with Channel name followed by suffix ".messageChannel-meta.xml".


4. Add the below content(Change the variable names and add/remove as needed).

Sample Code:
<?xml version="1.0" encoding="UTF-8"?>
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
    <masterLabel>SampleChannel</masterLabel>
    <isExposed>true</isExposed>
    <description>This is a sample Lightning Message Channel.</description>
    <lightningMessageFields>
        <fieldName>variable1</fieldName>
        <description>Variable 1</description>
    </lightningMessageFields>
    <lightningMessageFields>
        <fieldName>variable2</fieldName>
        <description>Variable 2</description>
    </lightningMessageFields>
</LightningMessageChannel>


5. Add the below in your package.xml.

    <types>
        <members>*</members>
        <name>LightningMessageChannel</name>
    </types>


6. Deploy the MessageChannel to the Source Org by selecting SFDX: Deploy this Source to Org.


Flow Button not Showing to Some Users in Salesforce

1. Enable the "Run Flows" Permission on the User Profiles that were not able to see the buttons.

2. If you are running a flow from a quick action using the Visualforce page. add the Visualforce page to the profile settings.

3. If the issue is in Case or Work Order object, check the below link

May 27, 2020

How to pass record Id in Flow to Lightning Component in Salesforce?

Aura Component Code:

<aura:component implements="lightning:availableForFlowScreens">
   
    <aura:attribute name="RecordId" type="String"/>
   
    <lightning:recordViewForm recordId="{! v.RecordId }" objectApiName="Account">
        <div class="slds-box">
            <lightning:outputField fieldName="Name" />
            <lightning:outputField fieldName="Industry" />
        </div>
    </lightning:recordViewForm>
   
</aura:component>


Flow:


Input Variable for capturing record id:


Pass RecordId which is the Input Variable:


Output:



May 26, 2020

lightning:treegrid select child rows upon selecting parent row in Salesforce

Sample Code:

Example.cmp:

<aura:component implements="force:appHostable"
                controller="AccountListController">
 
    <aura:attribute name="gridColumns" type="List" />
    <aura:attribute name="gridData" type="Object" />
    <aura:attribute name="selectedRows" type="list" />
   
    <aura:handler name="init" value="{!this}" action="{!c.fetchAccounts}"/>
   
    <lightning:treeGrid columns="{! v.gridColumns }"
        data="{! v.gridData }"
        keyField="Id"
        aura:id="mytree"
        onrowselection="{! c.onSelected }"
        selectedRows="{! v.selectedRows }"/>
       
</aura:component>


Example.js:

({
    fetchAccounts : function( component, event, helper ) {
        var columns = [
            {
                type: 'text',
                fieldName: 'Name',
                label: 'Account Name'
            },
            {
                type: 'text',
                fieldName: 'Industry',
                label: 'Industry'
            },
            {
                type: 'text',
                fieldName: 'FirstName',
                label: 'First Name'
            },
            {
                type: 'text',
                fieldName: 'LastName',
                label: 'Last Name'
            },
            {
                type: 'email',
                fieldName: 'Email',
                label: 'Email'
            }
        ];
        component.set('v.gridColumns', columns);
        var action = component.get("c.fetchAccts");
        action.setCallback(this, function(response){
            var state = response.getState();
            if ( state === "SUCCESS" ) {
                var data = response.getReturnValue();
                for ( var i = 0; i < data.length; i++ ) {
                    data[i]._children = data[ i ][ 'Contacts' ];
                    delete data[i].Contacts;

                }
                component.set( 'v.gridData', data );
            }
        });
        $A.enqueueAction(action);
    },
   
    onSelected : function( component, event, helper ) {
       
        var selectedRows = event.getParam( 'selectedRows' );
        var data = component.get( 'v.gridData' );
        var selectedData = [];
       
        for ( var i = 0; i < selectedRows.length; i++ ) {
           
            for ( var j = 0; j < data.length; j++ ){
               
                if ( selectedRows[ i ].Id == data[ j ].Id ) {
                   
                    var childrenRecs = data[ j ][ '_children' ];
                    selectedData.push( data[ j ].Id );
                   
                    for ( var k = 0; k < childrenRecs.length; k++ )
                        selectedData.push( childrenRecs[ k ].Id );   
                   
                }
               
            }
           
        }
       
        component.set( 'v.gridData', data );
        component.set( 'v.selectedRows', selectedData );
       
    }

})


AccountListController Apex Class:

public class AccountListController {

    @AuraEnabled
    public static List < Account > fetchAccts() {
        return [ SELECT Id, Name, Industry,
                ( SELECT Id, FirstName, LastName FROM Contacts )
                FROM Account LIMIT 100 ];
    }
   

}


Output:


May 25, 2020

Perform Synchronous Compile on Deploy

This feature is enabled automatically for production orgs but it's an opt-in feature for sandboxes.

Previously, installation and upgrades with large packages resulted in all classes not being compiled.  This causes serious app performance issues until all classes are compiled.

Each org’s Apex code is now automatically recompiled before completing a metadata deploy, package install, or package upgrade. This change in behavior improves performance following metadata deploys and package updates. Previously, a deploy, install, or upgrade could leave an org with invalidated code, causing reduced performance while Apex was recompiled.

This feature causes deployments to the org to invoke the Apex compiler and save the resulting bytecode as part of the deployment. A minimal increase in deployment times can occur, but Apex doesn’t need to be recompiled on first run. So the slight increase in deployment time can prevent performance issues on first run.

1) Go to Setup --> Apex Settings


2) Enable "Perform Synchronous Compile on Deploy"


Lightning Community Cloud Custom Theme with Common and Uncommon components in Salesforce

Sample Code:

<aura:component implements="forceCommunity:themeLayout" access="global" description="Sample Custom Theme Layout">
   
    <aura:attribute name="AppearInAll" type="Aura.Component[]" required="false"/>
    
    <div>
        <div>
            <!-- This will be avaliable in all pages --> 
            {!v.AppearInAll}
        </div>
        <div>
            {!v.body}
        </div>
    </div>
    
</aura:component>

Output:

Component added in AppearInAll will be available in all the pages where the Theme is selected.


May 20, 2020

Entitlement Templates in Salesforce

Entitlement templates let you predefine terms of support that users can add to products.

If Entitlement template is assigned to ProductA and if Asset is created with the ProductA, Entitlement Process from the Entitlement Template is automatically linked. You can see the Entitlements from the Asset Related List.

1. Sample Entitlement Processes.


2. Sample Entitlement Templates.


3. Sample Products with Entitlement Templates.





Asset Created with Product which has Entitlement Template:



May 19, 2020

lightning-record-form LWC in Salesforce Community

Sample Code:

LWC HTML:

<template>

    <div class="slds-box slds-theme_default">
        <lightning-record-form record-id={recId}
                            object-api-name={objectName}
                            layout-type="Full"
                            mode="view"
                            columns="2"
                            density="comfy"></lightning-record-form>
    </div>

</template>


LWC JavaScript:

import { LightningElement, wire, track } from 'lwc';
import { CurrentPageReference } from 'lightning/navigation';

export default class RecordPageLWC extends LightningElement {

    @track recId;
    @track objectName;

    @wire(CurrentPageReference)
    currentPageReference;

    connectedCallback() {
       
        const recrdId = this.currentPageReference.state.recId;
        const sobjName = this.currentPageReference.state.objNam;

        if ( recrdId )
            this.recId = recrdId;

        if ( sobjName )
            this.objectName = sobjName;
   
    }

}


LWC JavaScript meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightningCommunity__Page</target>
    </targets>
</LightningComponentBundle>


Output:
In the below example, I am passing recId and objNam parameters value in the URL.



Salesforce Event Monitoring notifications listening from Workbench

1. Go to Event Manager..


2. Enable the Event. In my case, I have enabled Lightning URI Event. Get the Subscription Channel.


3. Subscribe using the Subscription Channel in Workbench.

Output:


How to make radio button in front of label using Aura components in Salesforce?

Sample Code:

Component:

<aura:component implements="force:appHostable,forceCommunity:availableForAllPageTypes">
   
    <aura:attribute name="options" type="List" default="[
                                                        { 'value': 'option1', 'label': 'Sales' },
                                                        { 'value': 'option2', 'label': 'Force' }
                                                        ]"/>
    <aura:attribute name="value" type="String" default="option1"/>
   
    <div class="slds-box slds-theme--default">      
        <lightning:radioGroup name="radioGroup"
                              label="Radio Group"
                              options="{! v.options }"
                              value="{! v.value }"
                              type="radio"/>
    </div>
   
</aura:component>

Output:


May 18, 2020

Navigating to a Page in Lightning Community using Custom Lightning Component and pass list values

Create a Standard Page with the name "Sample":


Sample code:

Component1 cmp:

<aura:component implements="forceCommunity:availableForAllPageTypes" access="global" >  
      
    <aura:attribute name="Txt1" type="String" default=""/>  
    <aura:attribute name="Txt2" type="String" default=""/>  
      
    <div class="slds-box slds-theme_default">  
          
        This is component 1.<br/><br/>  
        <lightning:input type="text" value="{!v.Txt1}" label="Enter some text"/><br/>  
        <lightning:input type="text" value="{!v.Txt2}" label="Enter some text"/><br/>  
        <lightning:navigation aura:id="navService"/>  
        <lightning:button label="Navigate" onclick="{!c.navigateToComTwo}"/>  
          
    </div>  
      
</aura:component> 

Component1 JavaScript Controller:

({  
      
    navigateToComTwo : function( component, event, helper ) {  
          
        event.preventDefault();  
        var navService = component.find( "navService" );  
        var listVars = [];
        listVars.push( component.get( "v.Txt1" ) );
        listVars.push( component.get( "v.Txt2" ) );
        var pageReference = {  
            type: "comm__namedPage",  
            attributes: {  
                pageName: "sample"  
            },  
            state: {  
                sampleVar: listVars 
            }  
        };  
        sessionStorage.setItem( 'pageTransfer', JSON.stringify( pageReference.state ) );  
        console.log( 'State is ' + pageReference.state );
        navService.navigate( pageReference );  
          
    }  
      
}) 

Component2 cmp:

<aura:component implements="forceCommunity:availableForAllPageTypes" access="global" >  
      
    <aura:attribute name="Texts" type="String[]" default=""/>  
      
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>  
      
    <div class="slds-box slds-theme_default">  
          
        This is component two.<br/><br/>  
        Texts are <br/>
        <aura:iteration items="{!v.Texts}" var="obj">
            {!obj}<br/>
        </aura:iteration>
          
    </div>  
      
</aura:component> 

Component2 JavaScript Controller:

({  
      
    doInit : function( component, event, helper ) {  
          
        var resultMsg = sessionStorage.getItem( 'pageTransfer' );  
        
        if ( resultMsg ) {
            
            console.log( 'resultMsg is ' + JSON.parse( resultMsg ).sampleVar );
            component.set( "v.Texts", JSON.parse( resultMsg ).sampleVar );  
            
        }
          
    }  
      
}) 

Output:




May 16, 2020

Arrow Function in JavaScript

Arrow functions also called “fat arrow” functions are a more concise syntax for writing function expressions.
Arrow functions were introduced with ES6 as a new syntax for writing JavaScript functions.
fat arrow symbol ( => ).

Without Arrow Function:
testFunc = function() {
  return "Welcome to InfallibleTechie";
}


With Arrow Function:
testFunc = () => {
  return "Welcome to InfallibleTechie";
}


With Arrow Function with Parameters:
<p id="test"></p>
<script>
var hello;
hello = (val1, val2) => val1 + val2;
document.getElementById( "test" ).innerHTML = hello( 3, 2 );
</script>


Output is 5.

this keyword impact:
Arrow functions allow you to retain the scope of the caller inside the function.
The value of "this" inside a function can’t be changed. It will be the same value as when the function was called.
If you need to bind to a different value, you’ll need to use a function expression.

May 13, 2020

Test Class for EmailMessage and EmailMessageRelation in Salesforce

Sample Code:

Apex Class:

public class EmailMessageHandler {
   
    public static void insertEM( String recordId ) {
       
        EmailMessage emailMessage = new EmailMessage(); 
        emailMessage.status = '3'; // email was sent 
        emailMessage.fromName = 'Magulan Duraipandian'; // from name 
        emailMessage.subject = 'This is the Subject!'; // email subject 
        emailMessage.htmlBody = '<html><body><b>Hello</b></body></html>'; // email body 
        //Lead Id 
        String[] toIds = new String[]{ recordId };  
        emailMessage.toIds = toIds; 
        // additional recipients who don’t have a corresponding contact, lead or user id in the Salesforce org (optional) 
        //emailMessage.toAddress = 'emailnotinsalesforce@toexample.com, anotherone@toexample.com'; 
        insert emailMessage; // insert 
         
        // Add Email Message Relation for id of the sender 
        EmailMessageRelation emr = new EmailMessageRelation(); 
        emr.emailMessageId = emailMessage.Id; 
        emr.relationId = recordId; 
        emr.relationType = 'FromAddress'; 
        insert emr;
       
    }

}

Test Class:

@isTest
public class EmailMessageHandlerTest {

    @isTest
    public static void testEM() {
       
        Lead objLead = new Lead( LastName = 'Test', Company = 'Example', Email = 'test1@dgma.com' );
        insert objLead;
        Test.startTest();
        EmailMessageHandler.insertEM( objLead.Id );
        Test.stopTest();
       
    }
   
}

May 11, 2020

What is the difference between Live Agent and Embedded Service/Snap-Ins?

Embedded Service chat (formerly known as snap-in).
Live Agent
Live Agent connects customers with your support agents through web-based chat.
In order to browse the website when they are chatting with the agent, they have to minimize the chat window. But, in embedded service, chat stays on the same window even when they navigate and browse the website.

Embedded Service/Snap-Ins
This uses Live Agent but, with a simpler setup.
Lightning Experience must be enabled to set up Embedded Service.
Users can get answers to their questions by chatting with an agent while browsing the site.
After you’ve set up Chat and Omni-Channel to work together in Lightning Experience, give your customers a better chat experience with Embedded Service and Einstein Bots. Embedded Service lets you create a pre-chat form and custom branding with little to no code. Embed the chat window on your website and both your desktop and mobile customers can have the same chat experience. Einstein Bots lets you connect customers to an automated chat bot to answer questions and solve straightforward issues.

May 7, 2020

How to display set decimals for a number field in lightining:dataTable in Salesforce?

Sample Code:

Component:

<aura:component implements="force:appHostable"   
                controller="AccountListController">   
       
    <aura:attribute type="Account[]" name="acctList"/>   
    <aura:attribute name="mycolumns" type="List"/>   
       
    <aura:handler name="init" value="{!this}" action="{!c.fetchAccounts}"/>   
       
    <lightning:datatable data="{! v.acctList }"    
                         columns="{! v.mycolumns }"    
                         keyField="id"   
                         hideCheckboxColumn="true"/>   
       
</aura:component>


Component JavsScript Controller:

({   
       
    fetchAccounts : function(component, event, helper) {   
           
        component.set('v.mycolumns', [   
            {label: 'Account Name', fieldName: 'Name', type: 'text'},   
            {label: 'Created Date', fieldName: 'CreatedDate', type: 'date', typeAttributes: { 
                                                                            day: 'numeric', 
                                                                            month: 'short', 
                                                                            year: 'numeric', 
                                                                            hour: '2-digit', 
                                                                            minute: '2-digit', 
                                                                            second: '2-digit', 
                                                                            hour12: true}}, 
            {label: 'Annual Revenue', fieldName: 'AnnualRevenue', type: 'number', typeAttributes: {
                                                                                   minimumFractionDigits: 3,
                                                                                   maximumFractionDigits: 5}}
        ]);   
        var action = component.get("c.fetchAccts");   
        action.setParams({   
        });   
        action.setCallback(this, function(response) {   
               
            var state = response.getState();   
            if (state === "SUCCESS")    
                component.set("v.acctList", response.getReturnValue());               
               
        });   
        $A.enqueueAction(action);   
           
    }   
       
})


Apex Class:

public class AccountListController { 
     
    @AuraEnabled 
    public static List < Account > fetchAccts() { 
         
        return [ SELECT Id, Name, CreatedDate, AnnualRevenue FROM Account LIMIT 10 ]; 
         
    } 
     
}

Output:


May 5, 2020

How to find text between tags in Salesforce using Apex?

Sample Code:

String str = '<test>abc</test><test>xyz</test>'; 
Pattern TAG_REGEX = Pattern.compile( '<test>[a-z]*</test>' ); 
Matcher matcher = TAG_REGEX.matcher( str ); 
while ( matcher.find() ) { 

    String strOutput = matcher.group().replace( '<test>', '' ).replace( '</test>', '' ); 
    System.debug( strOutput ); 

}

Output:


Sample Code with Capital Letters and Space:

String str = '<test>abc ABC+</test><test>xyz XYZ-</test>';
Pattern TAG_REGEX = Pattern.compile( '<test>[a-zA-Z0-9\\s+-]*</test>' );
Matcher matcher = TAG_REGEX.matcher( str );

while ( matcher.find() ) {

    String strOutput = matcher.group().replace( '<test>', '' ).replace( '</test>', '' );
    System.debug( strOutput );


}


Output:

 

May 4, 2020

@InvocableVariable Example in Salesforce Flow

Flow:



Invocable Variable Configuration:



Apex Class:

global class FlowController {
        
    @InvocableMethod( label='Show Outputs' description='Getting multiple values' )
    global static List < FlowOutput > showOutputs( List < FlowInput > inputs ) {
        
        FlowInput objInput = inputs.get( 0 );
        List < FlowOutput > outputs = new List < FlowOutput >();
        FlowOutput objOutput = new FlowOutput();
        objOutput.str3 = objInput.str1;
        objOutput.str4 = objInput.str2;
        outputs.add ( objOutput );
        return outputs;
        
    }
    
    global class FlowInput {
        
        @InvocableVariable
        global String str1;
        
        @InvocableVariable
        global String str2;
        
    }
    
    global class FlowOutput {
        
        @InvocableVariable
        global String str3;
        
        @InvocableVariable
        global String str4;
        
    }
    
    

}

Output:



for:each in LWC HTML in Salesforce

Sample code:

HTML:

<template>

    <div class="slds-box slds-theme_default">
        <table class="slds-table slds-table_cell-buffer slds-table_bordered slds-table_col-bordered">
            <thead>
                <tr>
                    <th class="" scope="col">
                        <div class="slds-truncate" title="Account Name">Name</div>
                      </th>
                      <th class="" scope="col">
                        <div class="slds-truncate" title="Account Industry">Industry</div>
                      </th>
                      <th class="" scope="col">
                          <div class="slds-truncate" title="Account Type">Type</div>
                        </th>
                        <th class="" scope="col">
                          <div class="slds-truncate" title="Account Number">Account Number</div>
                        </th>
                        <th class="" scope="col">
                            <div class="slds-truncate" title="Site">Site</div>
                          </th>
                </tr>
            </thead>
            <tbody>
                <template for:each={accounts} for:item="acc">
                    <tr key={acc.Id}>
                        <td>{acc.Name}</td>
                        <td>{acc.Industry}</td>
                        <td>{acc.Type}</td>
                        <td>{acc.AccountNumber}</td>
                        <td>{acc.Site}</td>
                    </tr>
                </template>
            </tbody>
        </table>
    </div>   
   
</template>

 

JavaScript:

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

export default class Example extends LightningElement {

    @track accounts;
   
    @wire( fetchAccounts ) 
    caseRecord({ error, data }) { 
 
        if ( data ) { 
 
            this.accounts = data; 
 
        } else if ( error )
            console.log( 'Error is ' + JSON.stringify( error ) );
         
    }

}


JavaScript meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>     
    <targets>   
        <target>lightning__Tab</target>   
    </targets>
</LightningComponentBundle>


Apex Class:

public with sharing class ExampleController {

    @AuraEnabled(cacheable=true)
    public static List < Account > fetchAccounts() {

        return [ SELECT Id, Name, Industry, Type, AccountNumber, Site FROM Account LIMIT 10 ];
       
    }
   
}

 

Output:



Unable to view Connected Apps OAuth Usage

If you are unable to view Connected Apps OAuth Usage for any Connected app, make sure at least one user is using the app.

Next Automated Approver Determined By in Salesforce Approval Process

A hierarchy field(Lookup to user object) can be used here.

When a hierarchical field is selected, the same field will be available as an assigned approver option in approval steps.
Automatically assign using the user field selected earlier will be available in the Approval Step.


 



If a hierarchy field is selected, Use Approver Field of Object Owner check box will be available. If this check box is enabled, the approval will go the record owner's hierarchical field instead of the user who is submitting the record for approval.

Example:

UserA's manager is UserB.
UserX's manager is UserY.
Next Automated Approver Determined By is set to manager.
Opportunity Owner is UserA.

If Use Approver Field of Opportunity Owner is enabled,
1. If UserA submits the record for approval, it will go to UserB for approval since Opportunity owner is UserA.
2. If UserX submits the record for approval, it will go to UserB for approval since Opportunity owner is UserA.

If Use Approver Field of Opportunity Owner is disabled,
1. If UserA submits the record for approval, it will go to UserB since UserA's manager is UserB.
2. If UserX submits the record for approval, it will go to UserY since UserX's manager is UserY.