0% found this document useful (0 votes)
23 views26 pages

Salesforce Questions

The document outlines various Salesforce cloud solutions, including Sales Cloud, Service Cloud, Marketing Cloud, and others, each tailored for specific business needs. It also explains key Salesforce concepts such as converting relationships, Organization-Wide Defaults, Roll-Up Summary fields, and the differences between Page Layouts and Lightning Record Pages. Additionally, it covers security levels, user permissions, Flow Builder functionalities, and the use of Batch and Queueable Apex for processing records.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views26 pages

Salesforce Questions

The document outlines various Salesforce cloud solutions, including Sales Cloud, Service Cloud, Marketing Cloud, and others, each tailored for specific business needs. It also explains key Salesforce concepts such as converting relationships, Organization-Wide Defaults, Roll-Up Summary fields, and the differences between Page Layouts and Lightning Record Pages. Additionally, it covers security levels, user permissions, Flow Builder functionalities, and the use of Batch and Queueable Apex for processing records.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

1. Types of Salesforce Cloud?

Ans. Salesforce offers several cloud solutions, each designed to serve different
business needs. Here's a breakdown of the main Salesforce cloud types:
1. Sales Cloud
• Purpose: Helps manage sales processes, leads, opportunities, accounts, and
contacts.
• Key Features: Lead management, opportunity tracking, sales forecasting,
workflows, reports, dashboards.
2. Service Cloud
• Purpose: Manages customer service and support.
• Key Features: Case management, knowledge base, live chat, call center
integration, AI-powered service (Einstein), field service.
3. Marketing Cloud
• Purpose: Enables businesses to manage marketing campaigns and customer
journeys.
• Key Features: Email marketing, social media, advertising, marketing
automation, audience segmentation, personalization, journey builder.
4. Commerce Cloud
• Purpose: Supports both B2C and B2B e-commerce.
• Key Features: Personalized shopping experiences, mobile commerce, AI-
powered recommendations, order management.
5. Experience Cloud (formerly Community Cloud)
• Purpose: Builds branded portals, forums, and customer/member/partner
communities.
• Key Features: Custom portals, knowledge sharing, collaboration, integration
with CRM data.
6. Analytics Cloud (now part of Tableau CRM)
• Purpose: Provides advanced data analytics and business intelligence.
• Key Features: Data visualization, AI-driven insights, custom dashboards,
forecasting.
7. Integration Cloud
• Purpose: Connects Salesforce with other systems using APIs and integration
tools.
• Key Features: MuleSoft Anypoint Platform, API management, data integration
across systems.
8. Health Cloud
• Purpose: Tailored for healthcare organizations.
• Key Features: Patient profiles, care plans, coordination tools, HIPAA
compliance.
9. Financial Services Cloud
• Purpose: For banking, insurance, and wealth management.
• Key Features: Client profiles, relationship management, financial planning,
compliance tracking.

2. Can you explain how to convert a Lookup relationship to a


Master-Detail relationship in Salesforce?
Ans. Yes, converting a Lookup relationship to a Master-Detail relationship in
Salesforce is possible, but there are a few important conditions that must be
met.
First, I make sure that all child records have a value in the lookup field —
because a Master-Detail relationship doesn’t allow null values in the master
field. I usually run a SOQL query or report to verify that there are no blank values
in that field.
Once the data is clean, I go to Setup → Object Manager, select the child object,
and navigate to Fields & Relationships. I locate the lookup field and click Edit. If
the conditions are met, Salesforce will give me the option to change the
relationship type to Master-Detail.
After I select that, I save the changes. I also review the implications, such as
cascading delete behavior and ownership settings, since these are controlled by
the master object in a Master-Detail relationship.
So in short, it’s a simple UI-based change, but it requires careful data validation
and understanding of how the relationship affects record-level access and
sharing.

3. Can you explain Organization-Wide Defaults (OWD) and how


sharing rules fit into the sharing hierarchy?
Ans. Yes. In Salesforce, OWD (Organization-Wide Defaults) define the baseline
level of access that all users have to each other's records. It’s the most
restrictive level of access in the record-sharing model. We use it to enforce data
security by default, and then open up access through more permissive sharing
mechanisms as needed.
For example, if we set the OWD for the Account object to Private, that means
users can only see accounts they own unless additional sharing is configured.
From there, Salesforce uses a sharing hierarchy to determine how access can
be opened up. The general order is:
1. OWD (Organization-Wide Defaults) – Baseline/restrictive access.
2. Role Hierarchy – Users higher in the hierarchy can access records owned by
users below them.
3. Sharing Rules – Automatically grant access to records based on criteria or
ownership (e.g., share all accounts where industry = 'Banking' with the Finance
Team).
4. Manual Sharing – Record owners or users with full access can manually share
individual records.
5. Team Access – Like Account Teams or Opportunity Teams, used to give access
to specific users for collaboration.
6. Apex Sharing – Custom logic to share records using Apex code.
This layered approach allows for a flexible and secure data-sharing model. In
practice, I usually start with the OWD, define the role hierarchy carefully, and
then apply sharing rules or Apex sharing only where necessary to meet business
needs without overexposing data.

4. Explain Roll-Up Summary fields — when can you create them,


how do you create them, and what are they used for?
Ans. Roll-Up Summary fields in Salesforce are used to automatically calculate
values from related child records and display them on the parent record. They
are extremely useful for summarizing data like totals, counts,
minimum/maximum values, etc.
You can create a Roll-Up Summary field only when:
1. There is a Master-Detail relationship between the parent and child objects.
2. The Roll-Up Summary is being created on the parent object.
3. You are not using certain field types that are unsupported (e.g., formula fields
involving other roll-up summaries or text fields in some calculations).
So, for example, if you have a custom object called Invoice (child) and Account
as the master, you can create a Roll-Up Summary field on Account to count the
number of Invoices or sum the total invoice amount.
➢ Go to Setup → Object Manager, and select the Parent Object.
➢ Click Fields & Relationships, then New.
➢ Choose Roll-Up Summary as the field type.
➢ Name the field and choose the child relationship (object).
Choose the type of summary:
• COUNT – number of related records
• SUM – total of a numeric field
• MIN / MAX – smallest or largest value in a field
Optionally, set filters to calculate the roll-up only for certain records.
Save and add to page layout if needed.
5. Is there a default junction object already present in a Salesforce
org?
Ans. By default, Salesforce doesn't provide a specific standard object that's
called a 'junction object.' However, the concept of a junction object is
fundamental to handling many-to-many relationships, and Salesforce provides
standard objects that can act like junction objects in specific contexts.
A junction object is simply a custom object with two master-detail
relationships to two other objects, enabling a many-to-many relationship. You
often create it yourself in custom data models — for example, if a single Student
can enroll in multiple Courses, and a Course has many Students, you'd create a
junction object called Enrollment.
Example : OpportunityContactRole

6. What’s the difference between Page Layouts and Lightning


Record Pages in Salesforce?
Ans. Page Layouts and Lightning Record Pages both control how a record is
displayed in Salesforce, but they serve different purposes and work at different
levels in the user interface.
Feature Page Layout Lightning Record Page

Controls field Controls the overall layout,


Purpose visibility, related including components and
lists, buttons regions

Applies to the entire record


Applies to record page (header, sidebars,
Scope
detail section etc.)

Standard & custom


What it Fields, sections, components, tabs, visibility
Manages buttons, related lists rules

Where It’s Object → Page Lightning App Builder


Configured Layouts

Profile-based Can be assigned by App,


User Targeting Record Type, and Profile
assignment
Feature Page Layout Lightning Record Page

More traditional; Highly customizable;


Flexibility limited layout supports dynamic forms &
options filters

No, Lightning Record Pages


Classic are only for Lightning
Yes
Support Experience

7. What data types can be used in Salesforce formulas?


Ans. 1. Object-Level Security – "Can I access the object at all?"
• Controls whether a user can create, read, edit, or delete records of a specific
object.
• Managed through:
o Profiles – baseline access
o Permission Sets – additional access
• Example: A user may have access to the Contact object but not to the
Opportunity object.

2. Field-Level Security – "Can I see or edit this specific field?"


• Controls visibility and editability of individual fields on a record.
• Also set via Profiles and Permission Sets.
• Example: A user can access the Contact object, but the SSN field is hidden or
read-only.

3. Record-Level Security – "Which individual records can I see or edit?"


• Controls access to specific records within an object.
• Managed using:
o Organization-Wide Defaults (OWD) – baseline sharing (e.g., Private,
Public Read Only)
o Role Hierarchy – users higher in the hierarchy inherit access
o Sharing Rules – criteria-based or ownership-based record sharing
o Manual Sharing – user shares a record manually
o Apex Sharing – custom logic to share records via code
• Example: Two Sales Reps can access the Opportunity object, but each can only
see the opportunities they own.
Summary Table:
Security Managed Through
Controls Access To
Level
Entire object Profiles, Permission Sets
Object-level
(CRUD)
Specific fields in the Profiles, Permission Sets
Field-level
object
OWD, Roles, Sharing Rules,
Record-level Specific records Manual/Apex

8. Can you explain what Profiles, Permission Sets, Public Groups,


and Queues are in Salesforce?
Ans.
1. Profile
"A Profile controls what a user can do in Salesforce — like which objects they
can access, what fields they can see, and whether they can create or edit
records.
Every user must have one profile, and it sets their basic access level."
Example:
A Sales user’s profile might give access to Leads and Opportunities, while a
Support user’s profile gives access to Cases.

2. Permission Set
"A Permission Set is used to give a user extra access without changing their
profile.
It’s like a ‘bonus permission’ you can add on top of their profile."
Example:
If someone needs temporary access to Campaigns, I can assign them a
Marketing permission set instead of changing their whole profile.

3. Public Group
"A Public Group is a collection of users, roles, or other groups that we use to
share records or give access to folders.
It makes sharing easier by grouping people together."
Example:
I can share certain reports or records with the ‘Finance Team’ group instead of
picking users one by one.

4. Queue
"A Queue is like a waiting area for records that need to be worked on.
Records in a queue aren’t owned by any one person — anyone in the queue can
take them."
Example:
New leads can go into a Sales queue, and reps can pick the ones they want to
follow up on.

Closing Summary:
"In short:
Profiles define what users can do,
Permission Sets add extra permissions,
Public Groups help with sharing, and
Queues hold records until someone takes them.

9. Can you explain Flow Builder, types of flows, how they are called, and the major
elements used in flows?
Ans. Flow Builder is a no-code automation tool in Salesforce. I use Record-
Triggered Flows for automation, Screen Flows for guided user input, and Auto-
Launched Flows for logic reuse. With elements like Assignment, Get Records,
Decision, and Create/Update Records, I can build complex processes easily
and maintain them without Apex.
Yes, Flow Builder is a tool in Salesforce that lets me automate business
processes without writing code. It’s very flexible — I’ve used it in several real-
world scenarios to improve user experience and reduce manual work.
For example, I recently built a Record-Triggered Flow that runs when a new
Case is created. If the Case is marked as ‘High Priority’ and the customer is a
Platinum account, the flow:
• Automatically assigns the case to a VIP Support Queue,
• Sends an email notification to the manager,
• And updates a custom field on the Account to track the number of urgent cases.
This eliminated the need for support agents to manually escalate cases and
ensured that high-value customers were prioritized immediately.
I’ve also used Screen Flows to guide users through processes like creating a
Lead, qualifying it, and then converting it to an Opportunity — all from a single
screen. It helps reduce clicks and ensure data consistency.
In another project, I used an Auto-Launched Flow called from a Process Builder
to update child records when the parent record was updated. This saved us from
writing Apex triggers.

Record-Triggered Flow: For auto-updates on Case, Opportunity, or custom


objects.
Screen Flow: For guided forms like onboarding or data corrections.
Auto-Launched Flow: Reusable logic triggered from other Flows or Process
Builder.
Scheduled Flow: For weekly checks like sending reminder emails or updating
status fields.

Types of Flows & Their Usage


How It's Triggered /
Flow Type Usage Called

Runs automatically Automatically


Record-Triggered when a record is triggered by changes
Flow created, updated, or in data
deleted
Runs at a specific time Scheduled (like a
Scheduled-
and frequency without batch job)
Triggered Flow
user interaction

Displays a form or set Called from button,


Screen Flow of screens for user Lightning page, or
input Quick Action

Does backend logic Called from Apex,


Auto-Launched Process Builder,
without screens or user
Flow another Flow, or API
input

Triggered when a
Platform Event- Responds to Platform platform event is
Triggered Flow Events being published received

Multi-step flow with Triggered by record


Record-Triggered changes (more
approval and user
Orchestration advanced use cases)
tasks

Major Flow Elements (Commonly Asked in Interviews)


Element Purpose

Assignment Assign values to variables

Decision If/Else logic (like an IF condition)

Get Records Fetch records from Salesforce


Element Purpose

Create Records Insert new records

Update Records Modify existing records

Delete Records Remove records

Display fields and collect user input (only in Screen


Screen Flows)

Loop Iterate over a collection of items

Collection Modify or filter a collection


Sort/Filter

Subflow Call another flow from the current flow

Pause Wait for a condition

10. Write batch apex and quable apex for that batch class.
Ans. 1. Batch Apex
"Batch Apex is used when I need to process a large number of records (over
50,000) in Salesforce asynchronously. It breaks the data into small chunks,
called 'batches', and processes them one at a time.
I’ve used Batch Apex for tasks like:
• Updating millions of old records,
• Data clean-up jobs (like filling missing fields),
• Scheduled jobs that run weekly or nightly.
Because it works in chunks, it's efficient and avoids hitting governor limits."
Example: I used a Batch Apex class to update Status__c on all Accounts older
than 1 year — around 300,000 records — without hitting limits.
2. Queueable Apex
"Queueable Apex is used when I need to run smaller jobs asynchronously that
don’t exceed governor limits. It’s faster and easier than batch, and I often use it
for:
• Chaining jobs (one after another),
• Handling logic after DML operations,
• Sending bulk emails or making callouts.
It’s great when I need more control than Future methods and the volume is
manageable — typically under 50,000 records."
Example: I used Queueable Apex to send welcome emails to new users after
signup and also log activity in a custom object — all handled asynchronously.

Let's say we’re updating a custom field Status__c on Account records to 'Active' if
their Industry is 'Technology'.

AccountStatusBatch :-
public class AccountStatusBatch implements Database.Batchable<SObject> {

public Database.QueryLocator start(Database.BatchableContext bc) {


return Database.getQueryLocator([
SELECT Id, Industry, Status__c FROM Account WHERE Industry =
'Technology' ]); }
public void execute(Database.BatchableContext bc, List<SObject> scope) {
List<Account> accToUpdate = new List<Account>();
for (Account acc : (List<Account>)scope) {
acc.Status__c = 'Active';
accToUpdate.add(acc); }
update accToUpdate;
}
public void finish(Database.BatchableContext bc) {
System.debug('Batch Job Finished.');
}
}

AccountStatusQueueable:-
public class AccountStatusQueueable implements Queueable {
public void execute(QueueableContext context) {
List<Account> accList = [SELECT Id, Industry, Status__c FROM Account
WHERE Industry = 'Technology'];
for (Account acc : accList) { acc.Status__c = 'Active'; }
if (!accList.isEmpty()) {
update accList; }
}
}

11. Can we call future methods from a trigger?


Ans. Yes, we can call @future methods from a trigger, but there are some
important rules and best practices to keep in mind.
A @future method is used to run code asynchronously, like making a callout or
processing logic in the background — outside the main trigger context.
You can call a future method from a trigger, as long as:
• It’s a static method.
• It is annotated with @future.
• You don’t exceed the governor limit of 50 future calls per transaction.
I used a @future method in a trigger on the Contact object to send data to an
external system via HTTP callout, since callouts aren’t allowed directly in
triggers.

12. Can you explain how to call an LWC (Lightning Web


Component) from a Screen Flow and how to call a Flow from an
LWC?
1. Calling an LWC from a Screen Flow:
You can embed an LWC inside a Screen Flow using the Flow Screen
Component. This allows you to add custom functionality in your Flow, such as
dynamic UI elements or advanced logic, that is not possible with standard Flow
components.
Steps to call an LWC from a Flow:
1. Create the LWC: The LWC must be made available for Flow usage by setting the
target to lightning__RecordPage or lightning__AppPage, and it must be registered
with the Flow screen component.
2. Expose LWC for Flow:
o In the LWC, define public methods and properties that the Flow can
interact with.
o Use @api decorator to expose data and methods to Flow.
3. Add LWC to Flow Screen:
o In Flow Builder, drag the Lightning Web Component onto a screen in the
Flow.
o Set properties or pass data from Flow to the LWC.
Example Use Case:
Imagine you have an LWC that dynamically displays customer information from a
custom object. You can use a Screen Flow to collect input and then pass that
data to the LWC for real-time display or further manipulation.

2. Calling a Flow from an LWC:


You can invoke a Flow from an LWC using the Flow API (Flow.Interview) in
JavaScript. This enables you to trigger Flows programmatically from within the
LWC, giving you more control over when and how the Flow is executed.
Steps to call a Flow from an LWC:
1. Create the Flow: First, you need to have a Flow ready that you want to call from
your LWC.
2. Call the Flow in LWC:
o Use the Flow component to invoke the Flow.
o Pass input parameters (if any) and handle the flow outputs (if needed).

Example Code to Call Flow from LWC:


import { LightningElement } from 'lwc';
import { createRecord } from 'lightning/uiRecordApi';
import { Flow } from 'lightning/flowSupport';

export default class CallFlowFromLWC extends LightningElement {


flowName = 'Your_Flow_Name';
flowParams = {
inputVar1: 'value1',
inputVar2: 'value2'
};

handleFlowStart() {
const flow = this.template.querySelector('lightning-flow');
flow.startFlow(this.flowName, this.flowParams);
}
}

In this example:
• The lightning-flow component is used to embed the Flow in the LWC.
• The Flow is triggered via the startFlow() method, passing in any input parameters
required.

13. Can you explain Lightning Message Service (LMS) and its
usage?
Ans. Lightning Message Service (LMS) is a powerful tool in Salesforce that
allows components (both Aura and Lightning Web Components) to
communicate with each other on the same page without having to be in direct
parent-child relationships. This is especially useful when components are
loosely coupled or not in the same hierarchy but still need to share data.
Lightning Message Service (LMS) enables asynchronous, cross-component
communication without the need for a parent-child relationship. I use LMS
when components need to interact but are loosely coupled. It’s ideal for
sending notifications or data between components, even across pages or
browser tabs. It’s simple to implement with message channels, and I don’t need
Apex to make it work, which makes it very flexible and efficient for modern
Salesforce apps.

LMS is ideal in the following situations:


1. Cross-Component Communication: When components need to communicate
with each other but aren't directly related in terms of parent-child relationships.
o Example: A component displaying account details needs to
communicate with a component that displays related contacts.
2. Different Pages or Tabs: You can use LMS to send messages between
components on different pages or even tabs in the same browser. For example, if
you have multiple tabs open with different Salesforce pages, LMS allows the
components in these pages to communicate.
3. Loose Coupling: It allows you to decouple your components, which means that
one component does not have to know about the existence of another. This
results in better modularity and reusability.
4. Sending Notifications: LMS is great for sending notifications or alerts across
different components on the same page.

How It Works:
1. Message Channel:
o A message channel is created as a part of the LMS setup. It defines the
structure of the messages that will be sent and received.
o You define the message structure in an XML file that both the sending
and receiving components will use.
2. Publishers and Subscribers:
o Publisher: A component that sends messages. For example, a
component that triggers some action or event (e.g., a button click).
o Subscriber: A component that listens for the messages and takes action
accordingly.

Example of Usage:
1. Create a Message Channel:
In your project, you need to create a messageChannel folder with a .xml file that
defines the structure of the message.
xml
<messageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
<channelName>myMessageChannel</channelName>
</messageChannel>

2. Publisher (LWC Component):


This component sends a message to others using the defined message channel.
import { LightningElement } from 'lwc';
import { publish, MessageContext } from 'lightning/messageService';
import MY_CHANNEL from
'@salesforce/messageChannel/myMessageChannel__c';
export default class PublisherComponent extends LightningElement {
message = 'Hello from Publisher!';
@wire(MessageContext) messageContext;
handleSendMessage() {
publish(this.messageContext, MY_CHANNEL, { message: this.message });
}
}

3. Subscriber (LWC Component):


This component listens for the message from the publisher.
import { LightningElement } from 'lwc';
import { subscribe, MessageContext } from 'lightning/messageService';
import MY_CHANNEL from
'@salesforce/messageChannel/myMessageChannel__c';
export default class SubscriberComponent extends LightningElement {
receivedMessage = '';
@wire(MessageContext) messageContext;
connectedCallback() {
subscribe(this.messageContext, MY_CHANNEL, (message) => {
this.receivedMessage = message.message;
});
}
}

Advantages of Using Lightning Message Service:


1. Loose Coupling: Components don’t need to know each other directly, improving
modularity and reusability.
2. Cross-Component Communication: You can send and receive messages
across components that aren't in direct hierarchy relationships.
3. No Need for Apex: Unlike other communication methods like @AuraEnabled,
LMS doesn't require Apex code for communication, reducing complexity.
4. Message Channel Flexibility: Allows for sending complex data between
components without hard dependencies.

14. Can you explain the lifecycle of a Lightning Web


Component?
Ans. The lifecycle of an LWC is basically how the component behaves from the
moment it’s created, to when it updates on the screen, and finally when it’s
removed. Understanding this helps manage resources and controls how the
component interacts with the page.
I basically think of the lifecycle as a series of events. The constructor is where it
starts, connectedCallback is when the component hits the page,
renderedCallback is triggered whenever the UI changes, and
disconnectedCallback is like the ‘goodbye’ when it’s removed. Understanding
these hooks is key to making sure the component runs smoothly and cleans up
after itself.

Here’s how I usually break it down:

Constructor:
• This is the first thing that happens. It's like when a component is born, but it's
still not on the page yet.
• At this point, you can set up initial variables or do anything that's needed when
the component is first created.
Js :-
constructor() {
console.log('Constructor runs first');
}

connectedCallback():
• After the component is added to the page, this is where it comes to life.
• It’s a good place to do things like fetch data from an API or set up subscriptions
(for things like events or messages).
Js:-
connectedCallback() {
console.log('Component added to DOM');
}

renderedCallback():
• This runs every time the component renders, so it’s triggered when the
component is added, and also whenever any data changes and causes the
component to update.
• This is where you can manipulate the DOM or trigger actions after the
component has finished rendering.
Js:-
renderedCallback() {
console.log('Component rendered or re-rendered');
}

disconnectedCallback():
• This is called when the component is removed from the page (like if it’s
removed from the DOM or the page is refreshed).
• Good place to clean up things like event listeners or cancel any ongoing API
calls.
Js:-
disconnectedCallback() {
console.log('Component removed from DOM');
}

15. Can you explain how disconnectedCallback() works, and


how it interacts with setTimeout()?
Ans. disconnectedCallback():
• This is a lifecycle hook that runs when the component is removed from the
DOM. It's the clean-up stage of the component's life.
• You use it to clear up any side effects that might have been left behind when the
component was removed, like stopping timers, canceling network requests, or
removing event listeners.
How it works:
• When the component is removed from the page (like when the user navigates
away or the component is conditionally rendered), Salesforce automatically
calls the disconnectedCallback() method, giving you a chance to clean things
up.
Js:-
disconnectedCallback() {
console.log('Component is removed from the DOM!');
}

setTimeout() and its relationship with disconnectedCallback():


• setTimeout() is used to run a function after a specified delay, like a timer. It’s
asynchronous, which means it doesn't block other code from running while it's
waiting.
The Issue:
• If you set up a timer with setTimeout() in a component and then navigate away
or remove the component from the DOM before the timeout runs, the callback
function in the setTimeout() will still try to execute, even though the component
is no longer part of the page.
• This can cause errors or unexpected behavior because the component is no
longer available.
Solution:
• To avoid running tasks like setTimeout() after the component is removed, you
should clear the timeout inside the disconnectedCallback() method.
Js:-
export default class TimerComponent extends LightningElement {
timer;
connectedCallback() {
// Set up a timeout to run after 3 seconds
this.timer = setTimeout(() => {
console.log('Timeout ran!');
}, 3000);
}
disconnectedCallback() {
// Clear the timeout when the component is removed
clearTimeout(this.timer);
console.log('Timer cleared because component was removed');
}
}

In this example:
• When the component is added, a setTimeout() is set to run in 3 seconds.
• If the component is removed before those 3 seconds, disconnectedCallback()
gets triggered, and we use clearTimeout() to cancel the timer to avoid it running
after the component is gone.

16. Can you explain the @api, @wire, and @track decorators in
LWC?
Ans. @api (Public Property/Method)
• What it does: This decorator is used to mark a property or method as public,
meaning it can be accessed or modified by parent components. It makes the
property or method exposed to the outside world.
• Where it’s used: When you want a parent component to be able to interact with
a child component’s data or call a method.
Js:-
export default class ChildComponent extends LightningElement {
@api publicProperty = 'Hello from Child!'; // Can be accessed by parent
components
}

@wire (Wire Service - Reactive Data)


• What it does: This decorator is used to fetch data reactively from Salesforce.
You use @wire to automatically call an Apex method or get data from a
Salesforce service and automatically update your component when the data
changes.
• Where it’s used: When you need to fetch data from Salesforce (like querying
records) or other services, and you want the component to automatically update
when that data changes.
Js:-
import { wire } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';

export default class AccountList extends LightningElement {


@wire(getAccounts) accounts; // Automatically fetches and updates the data
}

@track (Reactive Property in LWC)


• What it does: This decorator is used to make an object or array reactive. It tells
LWC to track changes to the property and re-render the component when the
property changes. It’s mainly for more complex structures like arrays and
objects, where you want LWC to automatically update the DOM when something
inside that structure changes.
• Where it’s used: When you need to track changes in a property that is an array
or object. In most cases with primitive values (like strings or numbers), LWC
tracks changes automatically, but for objects/arrays, you need @track.
Js:-
export default class TrackerComponent extends LightningElement {
@track userDetails = { name: 'John', age: 25 }; // Automatically tracks changes
to object
updateName() {
this.userDetails.name = 'Jane'; // This will automatically trigger a re-render
}
}

17. How do you expose properties between a child and a parent


component in LWC?
Ans. Exposing Properties from Child to Parent:
To expose properties or methods from a child to a parent, you use the @api
decorator in the child component. This makes the properties or methods public
so that they can be accessed or modified by the parent component.
Child Component (Exposing properties)
Js:-
// childComponent.js
import { LightningElement, api } from 'lwc';

export default class ChildComponent extends LightningElement {


@api publicProperty = 'Hello from Child'; // This can be accessed by the parent

@api
changeMessage(newMessage) {
this.publicProperty = newMessage; // Method to change the value of
publicProperty
}
}
Explanation: In this example, the publicProperty is exposed to the parent
component because it is decorated with @api. Similarly, the changeMessage()
method is also exposed to allow the parent to modify the publicProperty.

Parent Component (Accessing child properties)


Js:-
// parentComponent.js
import { LightningElement } from 'lwc';

export default class ParentComponent extends LightningElement {


childComponent;

handleChangeMessage() {
// Accessing the public method of the child component to change its
property
this.childComponent.changeMessage('New Message from Parent');
}
}
Html:-
<!-- parentComponent.html -->
<template>
<c-child-component onmessagechange={handleChangeMessage}
ref="childComponent"></c-child-component>
</template>
Explanation: In the parent component, you can access and call the exposed
method or property of the child using a ref. In this case, the
handleChangeMessage() method triggers the child’s changeMessage() method
to modify the publicProperty in the child.

Exposing Properties from Parent to Child:


To expose properties from a parent to a child, you simply pass them as
attributes in the child component’s tag in the parent’s HTML.
Parent Component (Exposing properties)
Js:-
// parentComponent.js
import { LightningElement } from 'lwc';

export default class ParentComponent extends LightningElement {


parentMessage = 'Hello from Parent';
}
Child Component (Receiving properties)
Js:-
// childComponent.js
import { LightningElement, api } from 'lwc';

export default class ChildComponent extends LightningElement {


@api parentMessage; // Property exposed to receive data from the parent
}
Html:-
<!-- parentComponent.html -->
<template>
<c-child-component parent-message={parentMessage}></c-child-
component>
</template>
Explanation: The parent component has a property (parentMessage) that’s
passed to the child component as an attribute. The child component, by using
@api on the property, makes it reactive to changes from the parent. The child
can then use this property just like any other local property.

Summary:
• Exposing properties from Child to Parent: Use the @api decorator in the child
component to make properties and methods accessible to the parent
component.
• Passing properties from Parent to Child: Simply pass properties from the
parent to the child as attributes in the child’s tag, and use the @api decorator in
the child to make them reactive.

18. Can you explain the concepts of event bubbling, composed,


and shadow DOM in LWC?
Ans. Yeah, these concepts mostly relate to how events travel in LWC, especially
when you have nested components using the shadow DOM structure.

1. Event Bubbling:
• Think of bubbling like a chain reaction—when you fire an event from a child
component, it can bubble up to the parent, and then maybe to the grandparent,
and so on.
• In LWC, events don’t bubble by default. You need to explicitly enable it by
setting bubbles: true when dispatching the event.
Js:-
this.dispatchEvent(new CustomEvent('mycustomevent', {
bubbles: true
}));
Why it's useful:
I use bubbling when I want a parent component to catch an event fired by its
child—like when the child button is clicked, and the parent should respond.

2. Composed:
• composed: true allows the event to pass through the shadow DOM boundary.
• Without it, the event stays stuck inside the component, even if it bubbles. So if
you're firing an event from a child component inside a shadow DOM and want
the parent (outside the shadow) to catch it, you need composed: true.
Js:-
this.dispatchEvent(new CustomEvent('mycustomevent', {
bubbles: true,
composed: true
}));
Why it's useful:
If I have a deeply nested child and I want a top-level component to handle the
event, composed makes sure the event escapes the component’s shadow DOM
and reaches the top.

3. Shadow DOM:
• The shadow DOM is basically a way to encapsulate a component’s HTML and
CSS so that it doesn’t interfere with the rest of the page.
• Every LWC component has its own shadow DOM by default, which keeps its
style and structure private.
Why it's important:
It helps avoid conflicts—like one component’s styles accidentally changing
another’s. But it also means that normal DOM queries and events don’t cross
shadow boundaries unless you explicitly allow them using composed.

Quick Summary for Interview:


• bubbles: Controls whether an event can travel upward through the DOM tree.
Default is false.
• composed: Controls whether an event can cross the shadow DOM boundary.
Also false by default.
• shadow DOM: Keeps your component’s HTML and CSS isolated from others.
Great for modular and secure components.

19. What is a Mixed DML Operation in Salesforce, and how do


you resolve it?
Ans. Mixed DML happens when you're trying to perform DML operations on
setup and non-setup objects in the same transaction, and Salesforce doesn't
allow that by default.
Setup objects: These are things related to user access or configuration like User,
Profile, PermissionSetAssignment, Group, etc.
Non-setup objects: These are your regular business objects like Account,
Contact, Opportunity, Custom__c, etc.
I usually fix it by moving one of the operations to a @future or Queueable method
so they run in separate transactions. It’s a common issue in user provisioning or
automation scenarios.”
20. What are the available OWD (Organization-Wide Default)
settings in Salesforce?
Ans. For Standard and Custom Objects:
OWD Setting Meaning

Private Users can only see their own records.

Public Read Only Users can see all records, but only edit their own.

Public Read/Write Users can see and edit all records.

Controlled by Access is determined by the parent record’s sharing


Parent settings.

For Special Objects:


• Activities (Tasks and Events):
o Can be Private or Controlled by Parent.
• Cases and Opportunities:
o If Private, users only see their own.
o Can be Controlled by Parent if related to Accounts.
• Contacts:
o Can also be Controlled by Parent via the Account.

21. What is the difference between View All Records and View
All Data in Salesforce?
Ans. View All Records gives access to all records of a specific object, bypassing
sharing rules for that object only. View All Data gives access to all data in the
org, so it’s much broader and usually for admins.
1. View All Records – Object-Level Permission
• This permission lets a user see all records of a specific object, regardless of
ownership or sharing rules.
• It ignores OWD and sharing rules, but only for that object.
Example:
If I give a user View All on the Account object, they can see all Account records,
even if the OWD for Account is set to Private.
• Set via: Profile → Object Settings → Object Permissions

View All Data – System-Level Permission


• This is a high-level permission that gives access to all data in the org — across
all standard and custom objects.
• It’s usually reserved for admins because it bypasses all sharing rules, OWDs,
and role hierarchy.
Example:
If I have View All Data, I can see everything — Accounts, Opportunities, Cases,
custom objects — even if I don’t have access to them through roles or sharing.
• Set via: Profile → System Permissions

22. List of Major Salesforce Errors & Exceptions.


Ans.
Error / Exception Description (Quick and Practical)

Your code used too much processing time


1. CPU Time Limit Exceeded — limit is 10,000 ms (10 sec) in
synchronous and 60 sec in async.

You hit the limit of 100 SOQL queries in


2. Too Many SOQL Queries one transaction. Usually caused by SOQL
(101) inside loops.

You've used more than 150 DML


3. Too Many DML operations (like insert, update) in one
Statements (151) transaction.

You fetched more than 50,000 records


4. Too Many Query Rows using SOQL in one transaction. Use batch
(50,000) Apex if needed.

Your Apex code executed over 200,000


5. Too Many Script lines in one transaction. Refactor to
Statements (200,000) optimize logic.

Issues like inserting a duplicate, violating


6. DML Exception validation rule, or null required field.

You tried to access a method or property


7. Null Pointer Exception on a null variable. Common coding
mistake.

You're trying to access an index in a list


8. List Index Out of Bounds that doesn’t exist.
Error / Exception Description (Quick and Practical)

Error while running a SOQL query, like


9. Query Exception using querySingleResult() but getting 0 or
more than 1 row.

You tried to perform DML on setup and


10. Mixed DML Operation non-setup objects in the same
Error transaction.

A problem during a HTTP callout, like


11. Callout Exception timeout, invalid URL, or unhandled
response.

12. Uncommitted Work You tried to do a DML after a callout


Pending without using @future or Queueable.

Generic governor limit error — covers


13. System.LimitException limits like CPU time, heap size, SOQL
limits, etc.

Regex expression is too large or complex


14. Regex Too Complicated for Apex to process.

15. Malformed JSON You tried to deserialize invalid or broken


Exception JSON string.

You tried to access a field that doesn’t


16. SObjectException exist or is not populated on an SObject.

You exceeded the memory limit for your


17. Heap Size Limit Apex code. Clean up lists, reduce stored
Exceeded (6 MB / 12 MB) data.

18. Depth Limit Reached You hit the 16-level recursion limit,
(Trigger Recursion) usually due to triggers calling each other.

You’re trying to insert/update a field


19. Field Integrity Exception incorrectly — e.g., referencing a non-
existent record.

You're trying to use a constructor that


20. Constructor Not Defined doesn't exist (wrong number/type of
arguments).
Error / Exception Description (Quick and Practical)

In test classes: System.assert() failed —


21. Assert Exception expected vs actual values don’t match.

Occurs when unsafe string concatenation


22. SOQL Injection Risk is used in dynamic SOQL. (Caught during
code review.)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy