Concepts or coding lessons of Salesforce that you can implement easily

Get records from different Objects using Wire Method

How to use @Wire to get data for Batch of records ??

In LWC project, we usually have scenario where we have to retrieve different records from different object. For this we use Wire method but are you using 2 wire methods for this ?

Then you are doing multiple calls which decreases performance. 

LWC have 'getRecords' using this we can use wire adapter to get data for a batch of records at once.

As this process in Batch style, this reduces the number of network calls which indirectly increases LWC performance.

Syntax:

@wire(getRecords, { records: [ { recordIds: string[], fields: string[] } ] })


This will return 2 parameters
Results which is batch result
hasErrors which indicates if any result is failed.


Note : If you want to get data for a single record, use getRecord instead.


Here is the example you can use:

import { LightningElement, wire } from 'lwc';
import { getRecords } from 'lightning/uiRecordApi';
import CONTACT_EMAIL_FIELD from '@salesforce/schema/Contact.Email';
import USER_EMAIL_FIELD from '@salesforce/schema/User.Email';
import USER_NAME_FIELD from '@salesforce/schema/User.Name';

export default class RecordPickerDemo extends LightningElement {
    @wire(getRecords, { 
        records: [
            {
                recordIds : ['0050XXXXXX8QSMo'],
                fields: [USER_EMAIL_FIELD],
                optionalFields: [USER_NAME_FIELD],
            },
            {
                recordIds : ['0032XXXXXXnuFFf'],
                fields: [CONTACT_EMAIL_FIELD],
            },
        ],
    })
    wiredRecords;
}

Easily Iterate Map in Lightning Web Component

In LWC project, we usually stuck how to iterate Map in Lightning Web Component
Here is the example you can use to iterate Map.

1. Create Apex class StudentController.cls:

public class StudentController {
@AuraEnabled(cacheble=true)
public static Map<String, String> fetchStudentData(){
Map<String, String> mapStudentData = new Map<String, String>();
mapStudentData.put('Om','BCS');
mapStudentData.put('Sai','BTech');
mapStudentData.put('Ram','BE Computer Science');
mapStudentData.put('Radhe','BE Civil');
return mapStudentData;
}
}


2. Create LWC LWCStudentMap.html:

<template>
    <lightning-card icon-name="standard:account" variant="base" title="LWC Map Demo">
      <table class="slds-table slds-table_cell-buffer slds-table_bordered">
        <thead>
            <tr class="slds-line-height_reset">
                <th scope="col"> Name </th>
                <th scope="col"> Faculty </th>
            </tr>
        </thead>
        <tbody>
            <template for:each={mapStudentData} for:item="objMap">
                <tr class="slds-hint-parent" key={objMap.key}>
                    <th scope="col">
                        <div title={objMap.key}> {objMap.key} </div>
                    </th>
                    <th scope="col">
                        <div title={objMap.value}> {objMap.value} </div>
                    </th>
                </tr>
            </template>
        </tbody>
      </table>>
    </lightning-card>
</template>


3. Create LWC LWCStudentMap.js:

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

export default class LWCStudentMap extends LightningElement {
    @track mapStudentData = [];
    @track error;

    @wire(fetchStudentData)
    wiredData({ error, data }) {
      if (data) {
        console.log('Data', data);
        var consts = data;
        for(var key in consts)
            this.mapStudentData.push({value:consts[key], key:key});
      } else if (error) {
        console.error('Error:', error);
        this.error = error;
      }
    }
}


Output: 


Subscribe blog for More updates !!! 


Read More: WhatsApp on Salesforce Integration in 5 Steps
                    Which Salesforce API Do I Use in Integration?
                    When To Use Salesforce REST API  
                   When To Use Salesforce SOAP API 
                   When To Use Salesforce Bulk API 


Latest Salesforce Interview Questions and Answers:

Sharing and Visibility Scenario based Interview Questions Part 2

11. User A is on vacation and User B wants temporary access of records owned by User A, how to share those records?

Ans: For this we have to use "Login Access" feature to log in as another user. Enable "Manage Login Access Policies" checkbox under User B`s profile.


12. User A is not having CRED permission on Account Object even User A is not having VIEW ALL and MODIFY ALL permission and OWD is private still User A is able to Create record. What could be the possible reason ?

Ans: May be there is Apex class (without sharing) which have logic to create Account record.


13. User A have CREAD permission on Account Object and User B shares Account record with View access. User A is not Owner of that record but still can EDIT the record, what could be the reason ?

Ans: User A may be have Modify All Permission for account object.


14. Manager wants to see all records owned by their team members. How to achieve this without giving Full Permission?

Ans: Set Manager on higher in Role hierarchy. And Set OWD to Private and then create sharing rule to grant access to manager for their teams records.


15. User A and User B should not VIEW or MODIFY each other data, how to achieve this?

Ans: OWD must be Private. Users should not be higher each other in Role hierarchy. Both Users should not have VIEW ALL and MODIFY ALL permission on profile. WE have to check other sharing rules.


16. User A can see User B data, but User B not able to see User A data, what could be the reason ?

Ans: Check if both users are on same Role hierarchy, if yes then check profile. if profile also same then check is there any record level sharing like sharing rule, apex sharing process which shares data.


17. User A have Read and Edit access on Account object under Profile, User B manually shares account record with Read Access with User A, can User A EDIT that shared record ?

Ans: No, although User A have Read and Edit access on Profile, user A cannot EDIT shared record. User A only can EDIT those Account which he owns.


18. User A wants to share specific Opportunity with User B who is not in same role or hierarchy. How to achieve this?

Ans: We can achieve this using Manual Sharing. To share opportunity with other users who is not in same role or hierarchy, we can use Manual Sharing.


19. User A reported that he can see records which he should not have access, how to troubleshoot and resolve this ?

Ans: Check User profile and role hierarchy to ensure he is not granted access for those records.

Also review Sharing settings for objects

Check VIEW All and MODIFY All is disabled on profiles

Check if any permission set have this access

Check if he is member of any public group or queue

 

20. OWD for Account is Private and User A need to access few Account records, without changing OWD, how we can achieve this?

Ans: Use Manual Sharing and assign those few records with User A.



Read More: Sharing and Visibility Scenario based Interview Questions Part 1
                    


Latest Salesforce Interview Questions and Answers:

Sharing and Visibility Scenario based Interview Questions Part 1

1. User A manually share record with User B. User A left organization, can User B still access records shared by User A?

Ans: No, Once Owner changes, then Owner based sharing remove by Salesforce. New owner need to re-share record with User B.


2. What is Data Skew and Owner Skew ? How to avoid it.

Ans: If parent record have more than 10000 child record then its Data skew. 

If user is owner of more than 10000 records then its Owner Skew.  

We have to monitor if any parent have more child records and move those to other parent.

If we have default owner then use some other logic to make default owner to other users.


3. When Object level access and Record level access have a conflict then what happens.

For example, let's say we have account object User A and User B both have read and edit access account object. User A manually share account record with the User B but while doing manual share User A provide read access to the User B. so User B can edit that manually shared Account record ?

Ans: Whenever there is a Object level access and Record level access have calculated Salesforce give the restrict level access to the user, in our case User B cannot Edit record shared by User A even if he have access Read and Edit Access


4. For Account object, User B do not have Edit access on Object level access. and User A manually shared account with Read and Edit access with User B, is User B able to Edit account ?

Ans: No, as User B do not have Edit access on Object level access (Profile level)

 

5. Account have 2 record types X and Y. On Profile, User A have X record type access but do not have access for record type Y. Can User A view Y record type Account records ?

Ans: Yes, can VIEW Y record type records. Record type restrict only Create access.


6. We have User a and User B, User A is above in role hierarchy but no Edit access on Account object. User B have Edit access on Account. Does User A have can edit the same record.

Ans: No, as User A do not have Edit access on Account object, so even on above role hierarchy User A cannot Edit account record.


7. Share button is not visible on page layout, why ?

Ans: If OWD of object is Public read - write then no need of sharing button. If OWD is not Public read - write, then check page layout and add button.


8. You want to give permission to certain group of users to export data from Salesforce, how would you achieve this ?

Ans: Create permission set and enable Weekly Data Export permission. Assign this permission set to users who need access to export data.


9. User A do not have FLS for Email field on Contact object. Can User A able to global search based on Email field ?

Ans: Yes, User A can do global search and get records but when User opens record then can not see Email field on Contact record.


10. What is the difference between Queue and public group ?

Ans: Queue is used for record owner ship. WE can not create queue on objects

 Public group is used for record visibility. WE can create public groups on objects. WE can create nested public groups.


Subscribe blog for More updates !!! 



Read More: Sharing and Visibility Scenario based Interview Questions Part 2
                    


Latest Salesforce Interview Questions and Answers:

Lightning Web Component Interview Questions - Part 2

 11. Can I use multiple decorators for one property?

Ans:No, we cant use multiple decorators for same property.

12. Do we have application events in LWC?

Ans:We dont have application event as such in LWC like Aura rather we have LMS in LWC to communicate between components which are not part of same hierarchy.

13. How to navigate user from LWC component to record detail page?

Ans: We can do it using NavigationMixin service.

14. Get current user ID in LWC without apex?

Ans: Yes we can get current user ID without apex by simply importing

        import Id from ‘@salesforce/user/Id’

15. When do we face error of “Cant assign to Read only property” in LWC?

Ans: This error generally occurs on update of public property @api decorator variable value. Ideally you should clone the value then make the changes to it.

16. How can you make a Lightning Web Component available for use in the Salesforce App Builder?

Ans: You need to define a custom component in the meta.xml file of your LWC and set the isExposed attribute to true.

17. How do you make an HTTP callout from a Lightning Web Component?

Ans: You can use the fetch API to make HTTP callouts in LWC. Import the fetch method and use it to send requests to external services.

18. LWC has the @wire decorator to get the data from apex. But you are not getting the data from the server. What could be one of the reason?

Ans: First check whether you have used @AuraEnabled(cacheable=true) in the apex method.

19. How to get current record id in LWC

Ans: Use the 'lightning/pageReferenceUtils' module which provides utility functions to extract parameters, including the record ID, from the page URL.

        import { LightningElement } from ‘lwc’;

import { getRecordId } from ‘lightning/pageReferenceUtils’;

export default class MyComponent extends LightningElement {

recordId;

connectedCallback() {

this.recordId = getRecordId();

}

}

20. How to ensure that LWC respects FLS?

Ans: a. Check FLS in Apex :

Use the 'SECURITY_ENFORCED' annotation. The 'WITH SECURITY_ENFORCED' clause ensures that the query respects FLS, throwing an exception if the user lacks the necessary permissions.

public with sharing class AccountController {

@AuraEnabled(cacheable=true)

public static Contact getCon(Id conId) {

return [SELECT Id, Name FROM Contact WHERE Id = :conId WITH SECURITY_ENFORCED];

}

}

 b. Use Schema Methods in Apex

 c. Use Standard Components Where Possible: Use Lightning Data Service components


21. How do you use the Salesforce REST API in LWC ?

Ans: We can use the built-in fetch method to make API callout from LWC

import { LightningElement } from ‘lwc’;

export default class MyAPIComponent extends LightningElement {

connectedCallback() {

const endpoint = '/services/data/v53.0/query?q=SELECT+Name+FROM+Contact';

fetch(endpoint, {

method: 'GET',

headers: {

'Authorization': 'Bearer ' + authToken

}

})

.then(response => {

return response.json();

})

.then(data => {

console.log('Data '+data);

})

.catch(error => {

console.error('error '+error);

});

}


Subscribe blog for More updates !!! 



Read More: Lightning Web Component Interview Questions - Part 1
                    


Latest Salesforce Interview Questions and Answers:

Lightning Web Component Interview Questions - Part 1

1. We extends LightningElement in LWC, What is the reason?

Ans: LightningElement is custom wrapper on HTMLElement which actually contains all the lifecycle hooks methods like connectedCallback(), disconnectedCallback(), renderedCallBack(). We can use this methods in LWC

2. What is the Lifecycle in LWC?

Ans:

a. Parent Constructor is called

b. Public property are set on parent

c, Parent is inserted to DOM

d. Once parent is inserted to DOM, Connected callback is called on parent

e. From this connected callback as parent is already inserted, you can reference different DOM elements.

f. Parent is rendered

g. Once parent is rendered, Constructor is called on the child

h. Public property of child are set

i. Child is inserted to DOM

j. Once child is inserted to DOM, Connected callback is called on child

k. Child is rendered

l. Once child is rendered, child rendered callback is called

m. Once child rendered callback is called, then parents rendered callback is called.

3. Is @wire method called multiple times during lifecycle of component in LWC ?

Ans:Yes, @wire method called multiple times in LWC

4. If we parent component X and there are two component Y and Z as child components. How can we communicate between Y and Z ?

Ans: We should fire up event from child component Y to parent X then from parent X call attribute / function exposed (as @api) and pass data into Z component.

5. Can we do DML in method annotated with @AuraEnabled(cacheable= true)?

Ans: No, we cannot do DML inside any method annotated with cacheable = true , we will receive an error as DMLLimit Exception.

6. Can we call function annotated with @AuraEnabled(cacheable= true) imperatively ?

Ans: Yes

7. How to refresh cache when calling method imperatively?

Ans: We have to use getRecordNotifyChange(RecordIds) which refreshes the Lightning Data Service cache providing you the latest data this will work only if cacheable = true was there. Otherwise we will have to call the function again from our js to get the latest data.

8. What happens when bubbles : false and composed : false (Default behavior)?

Ans:This is the default behavior, and bubbles and composed are not required to be defined explicitly.

When this is in effect, the event would not bubble up the DOM, as well as it would not cross shadow boundary.

We can listen these event only via defining the event handler to component that fires the event.

9. What happens when bubbles : true and composed : false ?

Ans:  In this behavior, the event bubbles up the DOM, but don’t cross the shadow boundary. In simple terms, It bubbles up inside the current template, in which event is fired, but it would not cross it’s boundary.

For example :- There are two component, where parent component contain child component. If event is fired inside child component, the event only bubbles up inside child component, and it would not cross it’s boundary, and parent component will not be able to listen this event.

10. What does composed : true does in an event ?

Ans: These types of events can bubble up inside DOM and also able to cross shadow boundary.

    For example :- There are two component, where parent component contain child component. If event is fired inside child component, the event bubbles up and it would cross it’s boundary, and parent component will be able to listen this event.


Subscribe blog for More updates !!! 



Latest Salesforce Interview Questions and Answers:

Salesforce Interview Questions - Part 7



More Salesforce Blogs:

Difference Between Indirect Lookup and External Lookup In Salesforce
What is the use of nextStartDate in Salesforce?
Check out Salesforce Daily Limit Only in 5 Simplest Steps
Learning Pagination In Salesforce Is Not Difficult At All ! You Just Need 3 Easy Steps
How To Learn Get Field Values From Visualforce Page To Apex Class Controller Without Losing Your Mind
Main Difference Between ISBLANK And ISNULL in Salesforce
How To Get Total Amount Of Records Processed In Batch Job In 10 Minutes And Still Look Your Best 
Export VisualForce Data into Excel Sheet in 3 Easiest Steps
7 Easy Steps to Generate Apex Class From WSDL In Salesforce
Simplest Way To Find Number of Days Between Two Dates in Salesforce
3 Easy Steps To Send Emails With Attachment From Your Apex Class In Salesforce
How Insert Comma In Formula Fields Can Help You Improve Your Productivity
Simple Guidance For You In Access Of Subquery Field Value Using Apex - Upwards Traversal.
Access Subquery Field Value Using Apex in 2 Easy Steps- Downwards Traversal


How Learning Enable Inline Editing In Visual Force Pages Could Save Your Money And Time

Easily Get Custom Labels in LWC

In this blog we are going to learn how we can access custom labels in LWC

To access custom label use below syntax:

import varName from '@salesforce/label/c.companyDiscount';

Create Custom Label :



customLabels.html

<template>
<div class="slds-m-around_small"> 
Company Discount is => {discountDetails}
</div>
</template>

customLabels.js

import { LightningElement, track } from 'lwc';

import companyDiscount from '@salesforce/label/c.companyDiscount';

export default class CustomLabels extends LightningElement {

    @track discountDetails = companyDiscount;

}

Output:




 

Subscribe blog for More updates !!! 



Read More: WhatsApp on Salesforce Integration in 5 Steps
                    Which Salesforce API Do I Use in Integration?
                    When To Use Salesforce REST API  
                   When To Use Salesforce SOAP API 
                   When To Use Salesforce Bulk API 


Latest Salesforce Interview Questions and Answers:

Easily Navigate from one LWC to another LWC

 Here we are going to see Navigate from one LWC to another LWC.

To Navigate from one LWC to another LWC, we need to add LWC component into AURA component. and in Aura component we have to implements "lightning:isUrlAddressable".

In this example, i have create 2 LWC components (sourceLWC, targetLWC) and 1 AURA component - NavigateAuraToLWC.

1. sourceCmp.html

<template>
    <lightning-card icon-name="custom:custom35" variant="Narrow" title="Source LWC">
      <div class="slds-var-p-horizontal_small">
        <lightning-button
          variant="brand"
          label="Navigate"
          onclick={handleClick}
        ></lightning-button>
      </div>
    </lightning-card>
</template>

sourceCmp.js

import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';

export default class SourceCmp extends NavigationMixin(LightningElement) {
    handleClick(){
        let pageRef = {
            type : "standard__component",
            attributes: {
             componentName: "c__NavigateAuraToLWC"// namespace + __ + aura component
            },
            state:{
                c__codeName: 'Status'
            }
        };

        this[NavigationMixin.Navigate](pageRef);
    }
}

sourceCmp.js-meta.xml

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

2. NavigateAuraToLWC.cmp

<aura:component implements="flexipage:availableForAllPageTypes,
        lightning:isUrlAddressable" access="global">

    <aura:attribute type="String" name="codeName"/>

    <aura:handler name="init" value="{!this}" action="{!c.init}"/>
    {!v.codeName}

    <div class="slds-card">
        <c:targetCmp codeName="{!v.codeName}"/>
    </div>
</aura:component>  

NavigateAuraToLWCController.js

({
    init : function(component, event, helper) {        
        alert('in init');
        // myPageReference give "pageRef" varible created in sourceCode.js LWC
        var myPageReference = component.get("v.pageReference");
        // Access state parameter
        var propertyValue = myPageReference.state.c__codeName;
        alert('propertyValue=> '+propertyValue);
        component.set('v.codeName', propertyValue);
    }
})


3. targetCmp.html

<template>
    <lightning-card icon-name="custom:custom12"
        variant="Narrow" title="Target LWC">
      <div class="slds-var-p-around_large">
       <h1>I am in LWC target component : {codeName}</h1>
      </div>
    </lightning-card>
</template>


targetCmp.js

import { LightningElement, api } from 'lwc';

export default class TargetCmp extends LightningElement {
    @api codeName;
}


targetCmp.js-meta.xml

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

Output: 

After adding sourceCmp component into home page, 


Once Click on Navigate button, it shows below :


Subscribe blog for More updates !!! 


Read More: WhatsApp on Salesforce Integration in 5 Steps
                    Which Salesforce API Do I Use in Integration?
                    When To Use Salesforce REST API  
                   When To Use Salesforce SOAP API 
                   When To Use Salesforce Bulk API 


Latest Salesforce Interview Questions and Answers: