Hello Viewers,
At first I would like to say ' Thank You ' for all your support so far.
I wish each and everyone one a very happy new year.Good Luck.
A blog containing Salesforce coding examples in detail.It's a place where you can find solutions to the problems that you may face in your daily salesforce coding. Apex classes,visual force page,we services,Integration,plugins,extensions,Lightning web components,Aura components,Email Messages,Sales cloud,service Cloud,Marketing Cloud.Lightning Web components,salesforce.com, Salesforce Tips and Tricks,short cuts,ApexMocks,Stubs, visibility,Salesforce Shorts
Hello Viewers,
At first I would like to say ' Thank You ' for all your support so far.
I wish each and everyone one a very happy new year.Good Luck.
How to setup visualstudio code for Salesforce - Salesforce Globe For You
Solution:
Step 1: Install visualstudio code by navigating to the URL https://code.visualstudio.com/ and based on your system that you are using
download the vs code and install it.
Step 2: Install Salesforce CLI by navigating to the URL https://developer.salesforce.com/tools/sfdxcli and based on your system that you are using download and install it.
To confirm if salesforce cli is installed or not,go to command prompt and type sfdx.
if the command shows the version,usage and topics etc it means its successfully installed.
In case if you didn't get the above,it means Path is missing.You need to check environmental variables and make sure sfdx installation path(till bin folder) is added to path variable.
Step 4: Adding Salesforce Extension Pack
Go to vs code and click on extensions icon and Search Salesforce Extensions Pack and install it.
That's it,the vs code is ready to use.
Note: Make sure java is installed and path is set correctly.
Java runtime could not be located in visual studio code Salesforce - Salesforce Globe For You
Solution: This error generally occurs in case if java is not installed or java path is not set correctly.
Step 1: Go to the folder where java is installed and copy the url till bin folder as shown below
C:\Program Files\Java\jdk-17.0.1\bin
Step 2: Open the vs code
Go to File--> Preferences --> Settings
Search with Java home and you will get the screen as shown below
Set the java:home path by coping the url as shown in the image below
That's it.The issue gets resolved.
How to show the static resource image in visualforce email template - Salesforce Globe For You
Solution: Use <apex:image url="{!$Resource.staticresourcename}" width="50" height="50"/> to display image
Example:
<messaging:emailTemplate subject="Visualforce Email Template Demo" recipientType="User" relatedToType="Account">
<messaging:htmlEmailBody >
<html>
<body>
<div>
<apex:image url="{!$Resource.TestLogo}" width="50" height="50"/>
</div>
</body>
</html>
</messaging:htmlEmailBody>
</messaging:emailTemplate>
Output:
How to show today's date in visualforce email template - Salesforce Globe For You
Solution: Use {!TODAY()} to display today's date in visualforce email template.
Example:
Visualforce Email Template Code
<messaging:emailTemplate subject="Visualforce Email Template Demo" recipientType="User" relatedToType="Account">
<messaging:plainTextEmailBody >
Today Date : {!TODAY()}
Today Date(DD/MM/YYYY) : <apex:outputText value="{0,date, dd/MM/YYYY}">
<apex:param value="{!TODAY()}" />
</apex:outputText>
</messaging:plainTextEmailBody>
</messaging:emailTemplate>
Output:
How to parse the data stored as map(key,value) in custom Label in Apex - Salesforce Globe For You
Problem: Assume that the data in the custom label stored as shown below
key1:value1;key2:value2;key3:value3
Now get the value from custom label and prepare map.
Solution: Get the value from Label and then split using ';' and store it in string array.Now iterate that array and do split using ':' and finally prepare map.
Example: The MapValues label is created as shown below
Sample Code:
List<string> lstValues = system.label.MapValues.split(';');
Map<String,string> mapValues = new Map<String,string>();
for(String val : lstValues){
list<String> lstVal = val.split(':');
mapValues.put(lstVal[0],lstVal[1]);
}
system.debug('mapValues:'+mapValues);
system.debug('keyset:'+mapValues.keyset());
system.debug('values:'+mapValues.values());
Output:
How to hide/remove label(active/inactive) from toggle button in Lightning web component - Salesforce Globe For You
Solution: Set the attributes message-toggle-active and message-toggle-inactive to empty to remove the labels from Toggle button as shown below
<lightning-input message-toggle-active ="" message-toggle-inactive="" type="toggle" label="Toggle Checkbox" name="input"></lightning-input>
Example:
hideToggleButtonLabelLWC.html
<template>
<lightning-card title="Toggle Button by default in LWC Component">
<lightning-input type="toggle" label="Toggle Button" name="input"></lightning-input>
</lightning-card><br/>
<lightning-card title="Toggle Button after making both attributes to empty in LWC Component">
<lightning-input type="toggle" label="Toggle Button" name="input" message-toggle-active ="" message-toggle-inactive=""></lightning-input>
</lightning-card>
</template>
hideToggleButtonLabelLWC.js
import { LightningElement } from 'lwc';
export default class ToggleButtonLWC extends LightningElement {}
hideToggleButtonLabelLWC.js-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__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Output:
How to hide and show specific record details when multiple records are displayed based on click in Lightning Web component - Salesforce Globe for You
Problem: Assume a list of Lead records are displayed using LWC Component.Initially on load only 1 field of each record will be visible.If your want to see more fields,he can click 'Show More' to view more data and then he can click 'View Less' to hide the details.
Solution: In the list of records itself,introduce one boolean field to handle the hide and show details.When user clicks on specific record,change that record related boolean flag to toggle as done in the example below
Example:
Apex class:
public class LeadController {
@AuraEnabled
public static List<LeadData> getLeads() {
List<LeadData> lstLead = new List<LeadData>();
for(Lead objLead : [Select id,name,leadSource from Lead Limit 3]) {
LeadData objLeadData = new LeadData();
objLeadData.ShowDetails = false;
objLeadData.lead = objLead;
lstLead.add(objLeadData);
}
return lstLead;
}
public Class LeadData {
@AuraEnabled public Boolean ShowDetails {get;set;}
@AuraEnabled public Lead lead {get;set;}
}
}
showHideLWC.html:
<template>
<template for:each={lstLeadData} for:item="objLeadData">
<lightning-card key={objLeadData.lead.Id}>
<template if:false={objLeadData.ShowDetails} key={objLeadData.lead.Id}>
Lead: {objLeadData.lead.Name} <span data-id={objLeadData.lead.Id} onclick={handleToggle}><a>Show More</a></span>
</template>
<template if:true={objLeadData.ShowDetails}>
Lead: {objLeadData.lead.Name} <span data-id={objLeadData.lead.Id} onclick={handleToggle}><a>View Less</a></span>
<div>
<div>Name :{objLeadData.lead.Name}</div>
<div>Lead Id :{objLeadData.lead.Id}</div>
</div>
</template>
</lightning-card>
</template>
</template>
showHideLWC.js:
import { LightningElement,track } from 'lwc';
import getLeads from '@salesforce/apex/LeadController.getLeads';
export default class ShowHideLWC extends LightningElement {
@track lstLeadData;
connectedCallback() {
getLeads()
.then(result => {
this.lstLeadData = result;
console.dir(result);
console.table(result);
console.log(result);
})
.catch(error => {
this.error = error;
});
}
handleToggle(event) {
var leadId = event.currentTarget.dataset.id;
this.lstLeadData.forEach(function(objLeadData){
if(objLeadData.lead.Id == leadId) {
objLeadData.ShowDetails = !objLeadData.ShowDetails;
}
});
}
}
showHideLWC.js-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>52.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Output:
Solution: Use lightning-input with type= "toggle" to display toggle button as shown below
<lightning-input type="toggle" label="Toggle Checkbox" name="input"></lightning-input>
Example:
toggleButtonLWC.html
<template>
<lightning-card title="Toggle Button in LWC Component">
<lightning-input type="toggle" label="Toggle Button" name="input"></lightning-input>
</lightning-card>
</template>
toggleButtonLWC.js
import { LightningElement } from 'lwc';
export default class ToggleButtonLWC extends LightningElement {}
toggleButtonLWC.js-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__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Output:
If condition in lwc component - Salesforce Globe For You
Solution: <template if:true={condition}> </template>
Example:
ifConditionLWC.html
<template>
<lightning-card title="If condition LWC Component">
<div class="slds-m-around_medium">
<template if:true={bTrue}>
<div class="slds-m-vertical_medium">
This Will display only when boolean variable bTrue is true.
</div>
</template>
</div>
</lightning-card>
</template>
ifConditionLWC.js
import { LightningElement,track } from 'lwc';
export default class IfConditionLWC extends LightningElement {
@track bTrue = true;
}
ifConditionLWC.js-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__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Output:
System Administrator not able to login as other user in Salesforce - Salesforce Globe For You
Problem: When system Admin logged into the Salesforce org,and went to the users list,login button before the user is not visibile which is used for Admins to login as other user
Solution: 'Administrators Can Log in as Any User' setting should be enabled in order for Admins to get access to login as other user.
Go to Setup --> Security controls --> Login Access Policies.
Enable the checkbox next to 'Administrators Can Log in as Any User' as shown in the image below
Getting the values in Apex class but not in lightning component - Salesforce Globe For You
Problem: When using wrapper class, the wrapper variable data is shown in debug logs of apex but in LWC component ,the data is not shown.
Solution: When using wrapper class,even the wrapper variables needs to be @AuraEnabled annotation as shown below
public class PersonData {
@AuraEnabled public string name {get;set;}
@AuraEnabled public String id {get;set;}
}
Example:
Apex Class: DisplayDataController
public class DisplayDataController {
@AuraEnabled
public static List<PersonData> fetchData() {
List<PersonData> lstPersonData = new List<PersonData>();
for(integer i =0; i<2; i++) {
PersonData objPersonData = new PersonData();
integer j= i+1;
objPersonData.id = '00'+j;
objPersonData.name = 'Test '+j;
lstPersonData.add(objPersonData);
}
return lstPersonData;
}
public class PersonData {
@AuraEnabled public string name {get;set;}
@AuraEnabled public String id {get;set;}
}
}
displayData.html
<template>
<lightning-Card title="Person Data">
<div>
<lightning-datatable
key-field="id"
data={lstPerson}
columns={columns}>
</lightning-datatable>
</div>
</lightning-Card>
</template>
displayData.js
import { LightningElement,track } from 'lwc';
import personData from '@salesforce/apex/DisplayDataController.fetchData';
const columns = [
{ label: 'id', fieldName: 'id' },
{ label: 'name', fieldName: 'name'}
];
export default class DisplayData extends LightningElement {
@track lstPerson;
@track columns = columns;
connectedCallback() {
personData().then(result => {
this.lstPerson = result;
console.log('lstPerson',result);
})
.catch(error => {
this.error = error;
});
}
}
displayData.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>51.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Output:
How to remove or hide 'setup' link from specific users in salesforce - Salesforce Globe For You
Solution: Uncheck the “View Setup and Configuration” permission under the Systems Permission section of associated profile or permission set.
How to skip a particular piece of code while test class is running in apex - Salesforce Globe For You
Solution: Use Test.isRunningTest() This method returns true if this code is called from test method of test class.
So in case if you need to skip piece of code when test class is running,place that code inside if(!Test.isRunningTest()){}.
Example:
public class SkipCodeController {
public static void run() {
if(!Test.isRunningTest()) {
system.debug('This method runs in normal method call from normal class');
} else {
system.debug('This method runs only when called from Test Class');
}
}
}
Output: When you call this method like SkipCodeController.run() output will be
How to lock sobject records in Apex - Salesforce Globe For You
Solution: Use FOR UPDATE keyword in inline SOQL queries to lock sObject records.
Example: Select id,name from Lead Limit 1 FOR UPDATE
Sample Code:
List<Lead> lstLead = new List<Lead>();
for(Lead objLead : [Select Id,lastName from Lead Limit 1 FOR UPDATE]) {
objLead.lastName = 'Lead '+objLead.lastName;
lstLead.add(objLead);
}
if(!lstLead.isEMPTY()) {
update lstLead;
system.debug('lstLead '+lstLead[0].lastName);
}
Output:
Note: You can’t use the ORDER BY keywords in SOQL query where FOR UPDATE is used.
How to find the referenced apex controller in a lightning component(Aura or LWC) in salesforce with out looking into component code - Salesforce Globe For You
Solution: Go to setup --> Custom Code --> Lightning Components --> click on the respective component as shown in the image below.
The LWC dependencies section as shown in the image below gives the required information.
How to retrieve custom metadata records in visual studio code using package.xml - Salesforce Globe For You
Solution: Assume Test_Metadata_Records__mdt is the api name of the custom metadata object and First is the record created.
Use Test_Metadata_Records.First as members and CustomMetadata as name as shown below
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
<members>Test_Metadata_Records.First</members>
<name>CustomMetadata</name>
</types>
<version>51.0</version>
</Package>
Output:
How to prepare or get set of record ids from SOQL query without using for loop in apex - Salesforce Globe For You
Sample Code:
Set<Id> setLeadIds = new Set<Id>();
setLeadIds = new Map<Id,Lead>([Select id,name from Lead]).keyset();
system.debug('setLeadIds:'+setLeadIds);
Output
How to compare values of 2 different lists in apex - Salesforce Globe For You
Problem: I have 2 lists ,listA with some values and listB with some values.I need to compare listA and listB and return true if both are same else false.
Sample Code:
List<String> listA = new List<String>{'a','b','d','c'};
listA.sort();
List<String> listB = new List<String>{'a','d','b','c'};
listB.sort();
Boolean bBothListAreSame = false;
if(listA.size() == listB.size()) {
Boolean bBothSame = true;
for(integer i = 0; i<listA.size(); i++) {
if(listA[i] != listB[i]) {
bBothSame = false;
}
}
if(bBothSame == true) {
bBothListAreSame = true;
}
} else {
bBothListAreSame = false;
}
system.debug('Both Lists are same:'+bBothListAreSame);
Output:
How to convert comma separated string to a list in apex - Salesforce Globe For You
Problem: I have a string as a;b;c;d.and I want to convert that string value to array as new List<String>{'a','b','c','d'}
Sample Code:
String s = 'a;b;c;d';
List<String> lstAlphabet = new List<String>();
lstAlphabet = s.split(';');
System.debug('List is:::'+lstAlphabet);
Output:
How to convert array(list) to a string with values separated with semicolon in apex - Salesforce Globe For You
Problem: I have one list lstAlphabet as List<String> lstAlphabet = new List<String>{'a','b','c','d'}
I want to convert that list to string as a;b;c;d
Sample Code:
String strFinalString = '';
List<String> lstAlphabet = new List<String>{'a','b','c','d'};
for(String aphabet : lstAlphabet) {
if(!string.ISEMPTY(strFinalString)) {
strFinalString = strFinalString+';'+aphabet;
} else {
strFinalString = aphabet;
}
}
system.debug('Final String:::'+strFinalString);
Output:
How to retrieve remote site settings using package.xml in visual studio code - Salesforce Globe For You
Solution :use the below package.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
<members>*</members>
<name>RemotesiteSetting</name>
</types>
<version>52.0</version>
</Package>
Output:
How to remove border around icon in lightning web component(LWC) - Salesforce Globe For You
Solution: use variant="bare" for <lightning-button-icon> tag
Example:
removeBorderIconLWC.html
<template>
<lightning-card title="Remvoing Border around Delete Icon in LWC">
<lightning-button-icon icon-name="utility:delete" alternative-text="Delete" class="test slds-m-left_xx-small"
variant="bare" title="Delete"></lightning-button-icon>
</lightning-card>
</template>
removeBorderIconLWC.js
import { LightningElement } from 'lwc';
export default class RemoveBorderIconLWC extends LightningElement {}
removeBorderIconLWC.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>51.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Output:
How to hide label of lightning combobox or drop down in lightning web component(LWC) - Salesforce Globe For You
Solution: Use variant="label-hidden" or remove label="".if we remove label ,you can still find empty space for label.
hideLabelLightningInputLWC.html
<template>
<lightning-card title="Hide Label of Combobox">
Industry Drop Down with Label <br/><br/><br/>
<template if:true={industryPicklist.data}>
<lightning-combobox name="Industry" value={Industry} label="Industry"
options={industryPicklist.data.values}>
</lightning-combobox>
</template>
Industry Drop Down without Label <br/><br/><br/>
<template if:true={industryPicklist.data}>
<lightning-combobox name="Industry" value={Industry} label="Industry"
options={industryPicklist.data.values} variant="label-hidden">
</lightning-combobox>
</template>
Industry Drop Down without Label <br/><br/><br/>
<template if:true={industryPicklist.data}>
<lightning-combobox name="Industry" value={Industry}
options={industryPicklist.data.values} >
</lightning-combobox>
</template>
</lightning-card>
</template>
hideLabelLightningInputLWC.js
import { api,track,wire,LightningElement } from 'lwc';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';
export default class HideLabelLightningInputLWC extends LightningElement {
@api industry;
@track lstAccount = [];
@wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT }) accountMetaData;
@wire(getPicklistValues,{
recordTypeId: '$accountMetaData.data.defaultRecordTypeId',
fieldApiName: INDUSTRY_FIELD
}
) industryPicklist;
}
hideLabelLightningInputLWC.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>51.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Output:
Add Row funnctionality in LWC Salesforce - Salesforce Globe For You
ApexClass:
public class AddRowController {
@AuraEnabled
public static List<AccountWrapper> fetchAccounts() {
List<AccountWrapper> lstAccountWrapper = new List<AccountWrapper>();
for(Account objAccount:[Select id,name,Industry from Account limit 2]) {
AccountWrapper objAccountWrap = new AccountWrapper();
objAccountWrap.AccountId = objAccount.Id;
objAccountWrap.AccountName = objAccount.Name;
objAccountWrap.Industry = objAccount.Industry;
objAccountWrap.Del = false;
lstAccountWrapper.add(objAccountWrap);
}
return lstAccountWrapper;
}
@AuraEnabled
public static List<AccountWrapper> saveAccounts(List<AccountWrapper> lstAccountWrap) {
List<AccountWrapper> lstAccountWrapper = new List<AccountWrapper>();
List<Account> lstAccount = new List<Account>();
List<Account> lstAccountToDel = new List<Account>();
for(AccountWrapper objAccountWrap :lstAccountWrap) {
Account objAccount = new Account();
if(objAccountWrap.Del && objAccountWrap.AccountId != null) {
objAccount.Id = objAccountWrap.AccountId;
lstAccountToDel.add(objAccount);
} else {
objAccount.Id = objAccountWrap.AccountId;
objAccount.Name = objAccountWrap.AccountName;
objAccount.Industry = objAccountWrap.Industry;
lstAccount.add(objAccount);
}
}
if(!lstAccountToDel.isEMPTY()) {
Delete lstAccountToDel;
}
List<Database.upsertResult> result = Database.upsert(lstAccount,false);
for(Account objAccount:[Select id,name,Industry from Account where id in:lstAccount]) {
AccountWrapper objAccountWrap = new AccountWrapper();
objAccountWrap.AccountId = objAccount.Id;
objAccountWrap.AccountName = objAccount.Name;
objAccountWrap.Industry = objAccount.Industry;
objAccountWrap.Del = false;
lstAccountWrapper.add(objAccountWrap);
}
return lstAccountWrapper;
}
public with sharing class AccountWrapper {
@AuraEnabled public String AccountName {set;get;}
@AuraEnabled public String AccountId {set;get;}
@AuraEnabled public String Industry {set;get;}
@AuraEnabled public boolean Del {set;get;}
}
}
addRowLWC.html
<template>
<lightning-card title="Add Row Functionality">
<table class="slds-table slds-table_cell-buffer slds-table_bordered">
<thead>
<tr >
<th class="slds-is-resizable" scope="col">
<div>
Account Name
</div>
</th>
<th class="slds-is-resizable" scope="col">
<div>
Industry
</div>
</th>
<th >
<lightning-button-icon icon-name="utility:info" alternative-text="Info" class="slds-m-left_xx-small" title="Info" variant="bare"></lightning-button-icon>
</th>
</tr>
</thead>
<tbody>
<template if:true={lstAccount}>
<template for:each={lstAccount} for:item="objAccount" for:index="index">
<tr key={objAccount.AccountId} if:false={objAccount.Del}>
<th>
<lightning-input type="text" class="slds-truncate" data-id={index} title={objAccount.AccountName} value={objAccount.AccountName} variant="label-hidden" onchange={nameChange}></lightning-input>
</th>
<th>
<template if:true={industryPicklist.data}>
<lightning-combobox name="Industry" value={objAccount.Industry}
data-id={index} options={industryPicklist.data.values} onchange={industryChange} variant="label-hidden">
</lightning-combobox>
</template>
</th>
<th >
<lightning-button-icon data-id={index} icon-name="utility:delete" alternative-text="Delete" class="test slds-m-left_xx-small" title="Delete" variant="bare" onclick={deleteRow}></lightning-button-icon>
</th>
</tr>
</template>
</template>
</tbody>
</table>
<div>
<lightning-button variant="brand" label="Add Row" title="Add Row" onclick={addRow} class="slds-m-left_x-small"></lightning-button>
<lightning-button variant="brand" label="Save Accounts" title="Save Accounts" onclick={saveAccountData} class="slds-m-left_x-small"></lightning-button>
</div>
</lightning-card>
</template>
addRowLWC.html.js
import { api,track,wire,LightningElement } from 'lwc';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';
import fetchAccounts from '@salesforce/apex/AddRowController.fetchAccounts';
import saveAccounts from '@salesforce/apex/AddRowController.saveAccounts';
export default class AddRowLWC extends LightningElement {
@api recordId;
@track lstAccount = [];
@wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT }) accountMetaData;
@wire(getPicklistValues,{
recordTypeId: '$accountMetaData.data.defaultRecordTypeId',
fieldApiName: INDUSTRY_FIELD
}
) industryPicklist;
connectedCallback() {
fetchAccounts()
.then(result => {
if(result){
this.lstAccount = result;
}
})
.catch(error => {
this.loader = false;
this.error = error;
});
}
addRow(event){
let newRecord ={AccountId:null,AccountName:null,Del:false};
this.lstAccount.push(newRecord);
}
deleteRow(event) {
var selectedRow = event.currentTarget;
var key = selectedRow.dataset.id;
this.lstAccount[key].Del = true;
}
saveAccountData(event){
saveAccounts({lstAccountWrap:this.lstAccount})
.then(result => {
if(result){
this.lstAccount = result;
}
})
.catch(error => {
this.loader = false;
this.error = error;
});
}
nameChange(event){
var selectedRow = event.currentTarget;
var key = selectedRow.dataset.id;
this.lstAccount[key].AccountName = event.detail.value;
}
industryChange(event) {
var selectedRow = event.currentTarget;
var key = selectedRow.dataset.id;
this.lstAccount[key].Industry = event.detail.value;
}
}
addRowLWC.html.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>51.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Output:
How to get objectName from record Id in apex salesforce - Salesforce Globe For You
Solution:
Id recordId = '00Q0o00001fxEZiEAM';
Schema.SObjectType sobjectType = recordId.getSObjectType();
String sobjectName = sobjectType.getDescribe().getName();
system.debug('Object Name : '+sobjectName);
Output:
How to show delete icon in lightning web component(LWC) - Salesforce Globe For You
Solution: use <lightning-button-icon icon-name="utility:delete" alternative-text="Delete" class="test slds-m-left_xx-small" title="Delete"></lightning-button-icon>
deleteIconLWC.html
<template>
<lightning-card title="Delete Icon in LWC">
<lightning-button-icon icon-name="utility:delete" alternative-text="Delete" class="test slds-m-left_xx-small" title="Delete"></lightning-button-icon>
</lightning-card>
</template>
deleteIconLWC.js
import { LightningElement } from 'lwc';
export default class DeleteIconLWC extends LightningElement {
}
deleteIconLWC.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>51.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Output:
How to navigate to record view page on button click lwc - Salesforce Globe For You
Solution: use the lightning-navigation service.The base class needs to extend NavigationMixin and then use methods to achieve this.
Example:
navigateToRecordViewPageLWC.html
<template>
<lightning-card title="Navigate To Record View Page On Click">
<div class="slds-p-around_small">
<ul class="slds-m-around_medium">
<template for:each={lstAccount.data} for:item="account">
<li key={account.Id} data-id={account.Id} onclick={navigateToRecordViewPage} style="color:blue;
text-decoration:underline;cursor:pointer; ">
{account.Name}
</li>
</template>
</ul>
</div>
</lightning-card>
</template>
navigateToRecordViewPageLWC.js
import { LightningElement,track,wire} from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';
export default class NavigateToRecordViewPageLWC extends NavigationMixin(LightningElement) {
@track lstAccount;
@wire(getAccounts) wiredAccounts(data,error){
if(data){
this.lstAccount = data;
console.log(JSON.stringify(this.lstAccount));
} else {
console.log(error);
}
}
navigateToRecordViewPage(event) {
const selectedRecordId = event.target.dataset.id;
console.log('Event',event);
console.log('Event',selectedRecordId);
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: selectedRecordId,
actionName: 'view',
},
});
}
}
navigateToRecordViewPageLWC.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>51.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Output:
How to dynamically fetch recordId in LWC salesforce - Salesforce Globe For You
Scenario: When I drag this LWC component on a particular salesforce record page(for example any account record),I need to get it's Id and display it in this LWC Component.
Solution:Use @api recordId in LWC Component.
Example:
displayRecordIdInLwc.html
<template>
<lightning-card>
<div style="padding-left: 10px;"><strong>Record Id :</strong>{recordId}</div>
</lightning-card>
</template>
displayRecordIdInLwc.js
import { LightningElement,api } from 'lwc';
export default class DisplayRecordIdInLwc extends LightningElement {
@api recordId;
}
displayRecordIdInLwc.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>51.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Output:
How to get parent record related field values from a record in LWC Salesforce - Salesforce Globe For You
Scenario: From the contact record,we need to fetch it's parent Account related field (Account Name,Account Rating) values in LWC
Example:
displayParentRecordFieldLWC.html
<template >
<lightning-card title="Contact Record Data">
<div class="slds-m-around_medium">
<p>Contact Name: {contactName}</p>
<p>Account Name: {AccountName}</p>
<p>Account Rating:{AccountRating}</p>
</div>
</lightning-card>
</template>
displayParentRecordFieldLWC.js
import { LightningElement, wire,api,track } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import CONTACT_NAME_FIELD from '@salesforce/schema/Contact.Name';
import ACCOUNT_NAME_FIELD from '@salesforce/schema/Contact.Account.Name';
import ACCOUNT_RATING_FIELD from '@salesforce/schema/Contact.Account.Rating';
export default class DisplayParentRecordFieldLWC extends LightningElement {
@api recordId;
@track contact;
@wire(getRecord, { recordId: '$recordId', fields: [CONTACT_NAME_FIELD, ACCOUNT_NAME_FIELD,ACCOUNT_RATING_FIELD]})
contact;
get contactName() {
return getFieldValue(this.contact.data, CONTACT_NAME_FIELD);
}
get AccountName() {
return getFieldValue(this.contact.data, ACCOUNT_NAME_FIELD);
}
get AccountRating() {
return getFieldValue(this.contact.data, ACCOUNT_RATING_FIELD);
}
}
displayParentRecordFieldLWC.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>52.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Note: Drag this component in contact page.
Output:
How to show progress bar in lwc component - Salesforce Globe For You
Solution: Use lightning-progress-indicator component to show the progress of a process.
Example:
displayProgressBarLWC.html
<template>
<lightning-Card title="Progress Bar">
<div style="padding:5px;">
<lightning-progress-indicator type="base" current-step={currentState}>
<lightning-progress-step label="Step One" value="1">
</lightning-progress-step>
<lightning-progress-step label="Step Two" value="2">
</lightning-progress-step>
<lightning-progress-step label="Step Three" value="3">
</lightning-progress-step>
<lightning-progress-step label="Step Four" value="4">
</lightning-progress-step>
</lightning-progress-indicator>
</div>
<div> This Component show Progress.Use Previous and next buttons to navigate or change steps</div>
<div style="padding:5px;">
<lightning-button variant="brand-outline" label="Previous" title="Primary action with lighter look" onclick={handlePrevious} class="slds-m-left_x-small"></lightning-button>
<lightning-button variant="brand-outline" label="Next" title="Primary action with lighter look" onclick={handleNext} class="slds-m-left_x-small"></lightning-button>
</div>
</lightning-Card>
</template>
displayProgressBarLWC.js
import { LightningElement,api } from 'lwc';
export default class DisplayProgressBarLWC extends LightningElement {
@api currentState = 1;
handleNext() {
if(parseInt(this.currentState) != 4) {
var counter = parseInt(this.currentState);
counter = counter +1;
this.currentState = String(counter);
console.log(this.currentState);
}
}
handlePrevious() {
if(parseInt(this.currentState) != 1) {
var counter = parseInt(this.currentState);
counter = counter - 1;
this.currentState = String(counter);
console.log(this.currentState);
}
}
}
displayProgressBarLWC.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>51.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Output:
how to use console.dir and console.table to debug in javascript file lwc component - Salesforce Globe For You
Solution: console.log is used to display all properties of the javascript object.
Console.table is used to display in the form of table.
Example:
callApexMethodFromLWC.html
<template>
<lightning-Card title="Display Console">
<lightning-button variant="brand" label="Call Apex method" title="Call Apex method to display 5 Leads" onclick={callApexMethod} class="slds-m-left_x-small"></lightning-button>
<div style="height: 300px;">
<lightning-datatable
key-field="id"
data={lstLeads}
show-row-number-column="true"
columns={columns}>
</lightning-datatable>
</div>
</lightning-Card>
</template>
CallApexMethodFromLWC.js
import { LightningElement,track } from 'lwc';
import getLeads from '@salesforce/apex/LeadController.getLeads';
const columns = [
{ label: 'Id', fieldName: 'Id' },
{ label: 'Name', fieldName: 'Name'}
];
export default class CallApexMethodFromLWC extends LightningElement {
@track lstLeads;
columns = columns;
callApexMethod() {
getLeads()
.then(result => {
this.lstLeads = result;
console.dir(result);
console.table(result);
console.log(result);
})
.catch(error => {
this.error = error;
});
}
}
callApexMethodFromLWC.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>51.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Output:When you do inspect element and see the output will be
How to open salesforce org from visual studio code - Salesforce Globe For You
Solution: Use SFDX: Open Default Org from command palatte or use the following command from terminal
sfdx force:org:open
How to show a link with text in record detail page in salesforce - Salesforce Globe For You
Solution: We may need 3 fields to do it.
1) one text field to store the display text of the link
2) one url field to store the actual url
3)One formula field(text) to display the actual text with hyperlink.
Example:In Lead Object ,created 3 fields.
URL_Text__c text field
URL_Field__c url field
URL_Link__c formula field(text) HYPERLINK( URL_Field__c , URL_Text__c, 'Self')
Output:
How to use LWC Component as quick action in salesforce. - Salesforce Globe For You
LWC Component can be used in quick action by modifying the following attributes of it's meta file as below
<targets>
<target>lightning__RecordAction</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__RecordAction">
<actionType>ScreenAction</actionType>
</targetConfig>
</targetConfigs>
Example:
lwcCompForQuickAction.html
<template>
<lightning-quick-action-panel title="Quick Action Title">
Welcome to LWC Component Quick Action
<div slot="footer">
Footer
</div>
</lightning-quick-action-panel>
</template>
lwcCompForQuickAction.js
import { LightningElement,api } from 'lwc';
export default class LwcCompForQuickAction extends LightningElement {
}
lwcCompForQuickAction.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>52.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordAction</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__RecordAction">
<actionType>ScreenAction</actionType>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>
Output: