SF Learners Hub

MASTER SALESFORCE, CONQUER YOUR GOALS

Salesforce Interview Question – Part 6

Share This Post

Here are some potential line-based Salesforce interview questions that you could include in a blog post:

1. What is the difference between Flow and Trigger?

FlowTrigger
Visual workflow tool for designing declarative automation processes.Code is written in Apex that gets executed in response to specific events.
Declarative (no code)Programmatic (requires Apex code)
Point-and-click, no coding requiredRequires Apex code and development skills
Typically used for building UI-driven processes, such as wizards or guided interactions.No direct user interface; operates in the background.
Triggered by user interactions, record changes, platform events, or external systems.Triggered by specific events, such as record creation, update, or deletion.
Supports building complex multi-step processes with decision logic, loops, and screens.Typically used for specific record-level actions, often with complex business logic.
Can read, create, update, and delete records in a flow.Can perform complex data manipulations using Apex code.
Subject to governor limits, but generally easier to stay within them.Subject to governor limits; careful coding is required to avoid hitting limits.
Limited external integration capabilities.Can integrate with external systems using Apex code.
Easier to maintain and understand for admins and non-developers.Requires version control, testing, and deployment practices for code.
Well-suited for UI-driven processes, guided interviews, and simple automations.Suitable for complex business logic, data transformations, and integrations.

2: What are the lifecycle hooks in LWC?

Answer: In Lightning Web Components (LWC), the lifecycle hooks are:

  1. constructor(): Initializes the component.
  2. connectedCallback(): Invoked when the component is inserted into the DOM.
  3. renderedCallback(): Invoked after the component’s elements are rendered.
  4. disconnectedCallback(): Invoked when the component is removed from the DOM.
  5. errorCallback(): Invoked when there is an error during rendering, connecting, or updating.

3: What is the Purpose of @AuraEnabled and Cachable = true in LWC?

Answer:

  • @AuraEnabled:
    • It is used to expose Apex methods in Lightning components and is required for methods that are invoked by Lightning components.
    • Allows client-side JavaScript in Lightning components to call server-side Apex controller methods.
  • Cachable = true:
    • It is used to enable caching of the data returned by an Apex method in a Lightning web component.
    • Caching improves performance by allowing components to use the cached data instead of making additional server calls when the data is unchanged.

4: What is the Use of the @Wire Method?

5: when we are using imperative call or @wire Method in LWC?

Answer:

  • @Wire:
    • Used to wire an Apex method or a property to a component’s JavaScript file.
    • Automatically provisions data, making it available to the component and keeping it up-to-date.
    • Facilitates declarative data binding without the need for imperative Apex calls.

6: Create an LWC Component to show the List of 10 Opportunities.

<!-- opportunityList.html -->
<template>
    <lightning-card title="Opportunity List" icon-name="standard:opportunity">
        <div class="slds-m-around_medium">
            <ul>
                <template for:each={opportunities} for:item="opp">
                    <li key={opp.Id}>{opp.Name}</li>
                </template>
            </ul>
        </div>
    </lightning-card>
</template>
// opportunityList.js
import { LightningElement, wire } from 'lwc';
import getOpportunities from '@salesforce/apex/OpportunityController.getOpportunities';

export default class OpportunityList extends LightningElement {
    @wire(getOpportunities)
    opportunities;
}

7: Difference between Aura and LWC?

Aura ComponentsLightning Web Components (LWC)
Event-driven, component-based frameworkComponent-based framework
NoYes
Proprietary Aura syntaxStandard HTML and modern JavaScript syntax
Slower compared to LWCFaster performance due to native browser support
Supports a wider range of browsersUses native Shadow DOM, more modern browsers
Limited debugging capabilitiesImproved debugging with standard browser tools
Steeper learning curveEasier for developers familiar with modern web standards
Two-way data bindingOne-way data binding (can use reactive properties for two-way)
Less support for the compositionStrong support for component composition
Less emphasis on reusabilityEmphasizes component reusability
More challengingEasier integration with third-party libraries
Uses events, application events, and component eventsUses standard DOM events and custom events
Supports both Lightning Experience and Salesforce ClassicFocuses on Lightning Experience, with limited support for Classic
Follows Salesforce’s security modelFollows Salesforce’s security model

8: How to create a user on the save button click of the LWC Component?

Create an Apex Method:

public with sharing class UserCreationController {
    @AuraEnabled
    public static void createUser(String username, String email, String firstName, String lastName) {
        // Your user creation logic here
        // For example:
        User newUser = new User(
            Username = username,
            Email = email,
            FirstName = firstName,
            LastName = lastName
            // Add additional fields as needed
        );
        insert newUser;
    }
}

Call the Apex Method from LWC:

import { LightningElement, api } from 'lwc';
import createUser from '@salesforce/apex/UserCreationController.createUser';

export default class MyComponent extends LightningElement {
    @api username;
    @api email;
    @api firstName;
    @api lastName;

    handleSaveClick() {
        createUser({ 
            username: this.username,
            email: this.email,
            firstName: this.firstName,
            lastName: this.lastName
        })
        .then(result => {
            // Handle success
        })
        .catch(error => {
            // Handle error
        });
    }
}

Add the Save Button to your LWC Component:

<template>
    <lightning-button label="Save" onclick={handleSaveClick}></lightning-button>
</template>

9: What is the lifecycle of Aura Components?

10: What is the purpose of With Sharing & Without Sharing in Apex?

  1. With Sharing:
    • When a class is declared with sharing, the sharing rules of the current user are enforced. This means that the Apex code respects the record-level and field-level permissions defined by the organization’s sharing settings, sharing rules, role hierarchy, and manual sharing.
    • The with sharing keyword is often used for classes that should respect the organization’s security model, ensuring that users only have access to the records they are authorized to see.
    • For example, if a user does not have access to certain records due to their profile or sharing settings, attempting to query or update those records in a class declared with sharing will respect those restrictions.
  2. Without Sharing:
    • When a class is declared without sharing, the sharing rules of the current user are not enforced. This means that the Apex code ignores the organization’s sharing settings and gives the code full access to all records in the system, regardless of the user’s actual permissions.
    • The without sharing keyword is typically used for classes that require full access to records, such as data migration scripts, background processes, or reports where the user’s permissions should not restrict data access.
    • It’s important to use without sharing with caution, as it bypasses the organization’s security model and can potentially expose sensitive data to users who should not have access to it.

11: What is the Purpose of ui-record-API in LWC?

12: What is the Invocable in Apex?

Invocable methods are called natively from Rest, Apex, Flow, or Einstein bot that interacts with the external API source. Invocable methods have dynamic input and output values and support describe calls.

13: What is the purpose of Lightning Navigation Mixin in Salesforce?

14: What is the difference between SOQL and SOSL?

SOQLSOSL
Used for querying records from a single object or related objectsUsed for searching across multiple objects and fields
SELECT field1, field2 FROM Object WHERE conditionFIND {search_query} RETURNING Object (fields)
Primarily used for querying records of a specific objectSearches across multiple objects, looking for a match in any object
Supports querying related objects through relationshipsDoes not explicitly support querying related objects
Not designed for free-text searchDesigned for free-text search
Specifies fields to retrieve in the SELECT clauseReturns a predefined set of fields for matching records
Relies on a structured query language similar to SQLEmploys a search language for unstructured queries
Generally more efficient for querying specific recordsMore suitable for searching across multiple objects without knowing which object contains the required data
SELECT Name, Account.Name FROM Contact WHERE Account.Type = 'Customer'FIND {John Doe} RETURNING Contact, Account

15: On the Contact Object there is one field i.e. Contact Status and it is a picklist field and contains Approved and Rejected Fields Values. So whenever the status is Approved, store the current timestamp in the time field. How can we achieve this using a trigger?

trigger UpdateTimestampOnApproval on Contact (before update) {
    // List to store contacts that need timestamp update
    List<Contact> contactsToUpdate = new List<Contact>();
    
    // Iterate over the contacts in the trigger context
    for (Contact updatedContact : Trigger.new) {
        // Check if the Contact Status has been changed to Approved
        if (updatedContact.Contact_Status__c == 'Approved' && 
            Trigger.oldMap.get(updatedContact.Id).Contact_Status__c != 'Approved') {
            // If yes, update the timestamp field with the current date and time
            updatedContact.Approval_Timestamp__c = DateTime.now();
            // Add the contact to the list for update
            contactsToUpdate.add(updatedContact);
        }
    }
    
    // Perform the update if there are contacts to update
    if (!contactsToUpdate.isEmpty()) {
        update contactsToUpdate;
    }
}

16: How can you handle the Recursion in a trigger?

17: I want to update 500 contact Records at a time using a trigger.New(). at the same time, only a single record or multiple records came in the trigger.New()?

trigger Update500ContactsAtATime on Contact (before update) {
    // List to store contacts that need update
    List<Contact> contactsToUpdate = new List<Contact>();
    
    // Iterate over the contacts in the trigger context
    for (Contact updatedContact : Trigger.new) {
        // Apply your update logic here
        // For example, updating a field on the contact
        updatedContact.Field_to_Update__c = 'New Value';
        
        // Add the contact to the list for update
        contactsToUpdate.add(updatedContact);
    }
    
    // Perform the update for all contacts in bulk
    update contactsToUpdate;
}

18. how do we embed Visual Flow in the VisualForce page?

To embed a Visual Flow in a Visualforce page, you can use the <flow:interview> component. This component allows you to incorporate a Visual Flow into your Visualforce page. Here’s an example of how you can do this:

<apex:page>
    <apex:includeLightning />
    <flow:interview name="Your_Flow_Name" buttonLocation="bottom">
        <!-- You can add additional attributes here if needed -->
    </flow:interview>
</apex:page>

19. What is the use of an Attribute tag?

20. How to get the current User logged-in ID using Apex?

Ans. with the help of userinfo.getUserId();

21. How to call the Apex Method from the JavaScript?

22. What are the Different Methods of Batch Apex?

Batch Apex is a mechanism for processing large sets of records asynchronously, breaking them into smaller chunks to avoid hitting governor limits. Batch Apex classes must implement the Database.Batchable interface, which includes three key methods:

  • start: The start method is responsible for identifying the scope of records to be processed. It returns an iterable (query locator or iterable object) representing the records to be processed in the batch.
  • execute: The execute method is where the actual processing logic for each chunk of records occurs. It receives a set of records as input and performs the necessary operations on them.
  • finish: The finish method is called once all batches have been processed. It is useful for performing any cleanup or finalization logic.

23. Why we are using @Future Annotation?

In Apex, the @future annotation marks methods that should be executed asynchronously in the future. Salesforce operates in a multi-tenant environment, and there are certain governor limits in place to ensure fair resource allocation among different organizations using the platform. These limits can impact the execution of long-running or resource-intensive operations. To address this, Apex provides the @future annotation to allow for the execution of certain methods in a separate thread, independently of the main transaction.

24. What is the purpose of Getter and Setter Methods in Apex?

In Apex, which is a programming language used for building applications on the Salesforce platform, Getter and Setter methods are used to control access to the private variables of a class. These methods are part of the encapsulation mechanism and are crucial for maintaining the integrity of data within an object.

Here’s a brief explanation of Getter and Setter methods:

  • Getter Method: The primary purpose of a Getter method is to retrieve the value of a private variable (or property) in a class.
public dataType getVariableName() {
    // logic to retrieve the value
    return variableName;
}
  • Setter Method: The primary purpose of a Setter method is to set the value of a private variable in a class. It allows controlled modification of the variable.
public void setVariableName(dataType newValue) {
    // logic to validate and set the value
    variableName = newValue;
}

25. What is the Purpose of Database.Stateful in Apex?

The Database.Stateful interface in Apex is used to declare a class as “stateful” within the context of a batch Apex job. In Apex, batch processing is a way to process a large number of records in chunks (batches) asynchronously. Normally, the state of variables in a class is not preserved between batches, as each batch is processed independently. However, by implementing the Database.Stateful interface, you indicate that certain variables in the class should retain their values across multiple batches in a single execution of the batch job.

26. Write a Function to return the list of Leads based on the State.

27. Write a trigger to find the duplicate account based on the phone number.

trigger DuplicateAccountTrigger on Account (before insert, before update) {
    // Set to store phone numbers of Accounts being inserted or updated
    Set<String> phoneNumbers = new Set<String>();
    
    // List to store duplicate Account records
    List<Account> duplicateAccounts = new List<Account>();
    
    // Iterate through Accounts to gather phone numbers
    for (Account acc : Trigger.new) {
        // Check if the Account has a phone number
        if (acc.Phone != null && acc.Phone != '') {
            // If a phone number already exists in the set, add the Account to the duplicate list
            if (phoneNumbers.contains(acc.Phone)) {
                duplicateAccounts.add(acc);
            } else {
                // Otherwise, add the phone number to the set
                phoneNumbers.add(acc.Phone);
            }
        }
    }
    
    // Query for existing Accounts with the same phone numbers
    List<Account> existingAccounts = [SELECT Id, Name, Phone FROM Account WHERE Phone IN :phoneNumbers];
    
    // Compare existing Accounts to Accounts being inserted or updated
    for (Account acc : existingAccounts) {
        for (Account newAcc : Trigger.new) {
            // Check if the Account being inserted or updated is different from the existing Account
            if (acc.Id != newAcc.Id && acc.Phone == newAcc.Phone) {
                duplicateAccounts.add(newAcc);
            }
        }
    }
    
    // If duplicate Accounts are found, add error messages
    for (Account dupAcc : duplicateAccounts) {
        dupAcc.addError('Duplicate Account found with the same phone number.');
    }
}

28. Write a Query to find the duplicate Account using the phone number.

SELECT Phone, COUNT(Id) 
FROM Account 
WHERE Phone != null 
GROUP BY Phone 
HAVING COUNT(Id) > 1

29. Can we call Batch Class From Future Methods?

No, it’s not possible to directly call a Batch class from a future method in Apex.

30. How we can call Apex Class from flow?

We can use the ‘Apex’ action element available in Flow Builder to call an Apex class from a flow in Salesforce. This class should be annotated with @InvocableMethod to make it available for use in flows.

31. I have one field on the Account object i.e. No of Employees. So Write a trigger to create a Contact associate with the particular account based on the given No of employees.

trigger CreateContactsOnAccount on Account (after insert, after update) {
    // List to store contacts to be inserted
    List<Contact> contactsToInsert = new List<Contact>();
    
    // Iterate through the triggered accounts
    for (Account acc : Trigger.new) {
        // Check if the 'No of Employees' field has changed or if it's a new Account
        if ((Trigger.isInsert || Trigger.oldMap.get(acc.Id).No_of_Employees__c != acc.No_of_Employees__c) && acc.No_of_Employees__c != null) {
            // Determine the number of contacts to create based on the 'No of Employees' field
            Integer numberOfContacts = acc.No_of_Employees__c;
            
            // Create contacts and associate them with the account
            for (Integer i = 0; i < numberOfContacts; i++) {
                Contact newContact = new Contact(
                    FirstName = 'ContactFirstName', // You may want to customize these values
                    LastName = 'ContactLastName' + i,
                    AccountId = acc.Id
                    // Add more fields as needed
                );
                contactsToInsert.add(newContact);
            }
        }
    }
    
    // Insert the created contacts
    if (!contactsToInsert.isEmpty()) {
        insert contactsToInsert;
    }
}

32. Write a SOQL Query to fetch the no of accounts that contain more than 3 contacts.

SELECT COUNT(Id), AccountId
FROM Contact
GROUP BY AccountId
HAVING COUNT(Id) > 3

33. What is the return type of the Start method in Batch Apex?

In Apex, the start method in a Batch Apex class returns either a Database.QueryLocator or an iterable (such as a List or Set).

34. Write an Apex Function to return the list of Leads based on the State.

public class LeadController {

    public static List<Lead> getLeadsByState(String targetState) {
        List<Lead> leadsList = new List<Lead>();
        
        // Query for leads based on the specified state
        leadsList = [SELECT Id, Name, Company, State FROM Lead WHERE State = :targetState];
        
        return leadsList;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Extract Valuable Data with Salesforce OCR

Revolutionize the way you handle and utilize your documents with OCR in Salesforce. Optical Character Recognition will enhance your data management and streamline business processes.