Back to Top
Showing posts with label Salesforce Developer. Show all posts
Showing posts with label Salesforce Developer. Show all posts

Salesforce Developer Interview Questions

Posted on TimeJanuary 7, 2026

 Q:1 Asynchronus Apex

Ans: If we have to run some job that will take some time then in the case of synchronous apex we will get the limit error, heap size error, or timeout error. To avoid such issues, we can do those long-running or time-consuming operations using Asynchronous apex which will run in a separate thread and will not impact the main thread. So Asynchronous Apex is used to run the process in a separate thread at a later time.

Increase User Efficiency
More Heap Size and Higher Governer limit
Better Scalability

Batch Apex
Future methods
Queueable Apex
Scheduled Apex

Q.2 Where we can use Asynchronous Apex?
Sending Email to the user.
Calling an external system for multiple records
Schedule a job for a specific time
Chaining apex code execution which might use

Q. 3 Can a future method call another non-future method to process tasks like callouts, and have those methods return data to the future method for further processing?

No, we can not call future methods from the future method.

Q:4 How many Schedulable Apex jobs can you have at one time? In other words, what is the maximum number of Apex classes that can be scheduled concurrently?
100

Q:5  Why sObject parameters not supported in future methods?
The sObject might change between the time we call the method and the time it executes that’s why sObjects can’t be passed as arguments to future methods. In this case, the future method will get the old sObject values and might overwrite them.

Q:6  Can I call Queueable from a batch?
Yes, But it is limited to just one System.enqueueJob call per execute in the  Database.Batchable class. Salesforce has imposed this limitation to prevent explosive execution.

Q:7 How Future method helps in avoiding Mixed DML errors?

There are 2 kinds of sObjects in salesforce.
1. Non-Setup: Account, opportunity, etc
2. Setup: User, groups,Queue etc
If we are performing DML on both kinds of sObject in a single transaction, the system doesn’t allow it and throws an exception called Mixed DML exception, stating that a transaction can not have a Mixture of DML operation(Setup and Non-Setup).

Q.8 What is Database.QueryLocator & Iterable<sObject>?

In Database.QueryLocator, we use a simple query (SELECT) to generate the scope of objects. The governor limit for the total number of records retrieved by SOQL queries is bypassed, i.e. it can return up to 50 million records.

In Iterable<sObject>, we can create a custom scope for processing, which would be not possible to create using SOQL where clauses. the governor limit for the total number of records retrieved by SOQL queries is still enforced.


Topics For Salesforce Developer Interview Questions

Before attending any Interview, you should revise some topic in Salesforce.


Topics:

Admin

  • Report
  • Dashboard
  • Data Modeling (Object, Field, Relationship)
  • Validation Rule 
  • Record Type 
  • Page Layout
  • Automation Tool(Flow, Approval Process,Process Builder and Workflow)
  • Data Security - Object Level Security, Field Level Security,Record Level Security 
  • (Profile, Permission Set, OWD, Role Sharing Rule, Mannual Sharing)
  • Sales Cloud (If you are in Sales Cloud)
  • Service Cloud (If you are in Service Cloud)
  • Community Cloud/Experience Cloud
  • Assignment Rule
  • Auto Responsive Rule
  • Web To Lead 

Development

  • Apex Programming(Apex class and trigger)
  • Asynchronous Apex: Learning about future methods, batch Apex, queueable Apex, and scheduled Apex for long-running operations.
  • Test Class - Best Practices of Test Class, Some Annotation that are used in Test class 
  • LWC:
    • Lifecycle hook
    • Aura Vs LWC
    • Communication between Component. (Parent to Child, Child to Parent)
    • Way of fetching data from apex
    • Decorators
    • LMS
    • Pub Sub Model
  • SOQL AND SOSL - Parent to Child Relationship Query and Child to Parent Relationship Query, Query with date, filter
  • Governor Limits
  • Integration:
    • REST and SOAP API
    • Inbound and Outbound Integration
    • Restful Resource
    • Authorisation vs Authentication
    • Remote Site Setting
    • Named Credential
    • Connected App
    • Workbench/Postman
  • Deployment:
    • Vscode
    • Change Set
    • Git
    • Sandboxes

By diving deep into these topics, you will be well-equipped to handle both configuration tasks (Admin side) and custom development tasks (Developer side), giving you an edge in job roles, interviews, and real-world problem-solving.

Essential Topics for Salesforce Developer Interview Preparation

Posted on TimeJune 25, 2024

Preparing for a Salesforce Developer interview requires mastering various crucial topics. Here’s a structured guide to help you focus your preparation:

1. Salesforce Fundamentals: 

  • Architecture: Understand multi-tenant architecture and metadata-driven development.
  • Governor Limits: Learn limits and best practices for optimizing performance.
  • Data Modeling: Design and implement objects, fields, relationships, record types, page layouts, and validation rules.


  • 2. Apex Programming:


  • Syntax and Data Types: Master Apex syntax, variables, loops, conditionals, and data structures.
  • Triggers: Know trigger context variables, execution order, and design patterns.
  • Batch and Scheduled Apex: Process data asynchronously and schedule tasks.

  • 3. Visualforce Pages and Lightning Components: 

  • Visualforce: Create custom UIs and integrate with Apex logic.
  • Lightning Components: Understand Aura components and Lightning web components

  • 4. Integration:


  • APIs: Use REST and SOAP APIs for external system integration.
  • Apex REST Services: Develop and consume RESTful services.
  • Data Management: Utilize Data Loader and manage data import/export.

  • 5. Salesforce DX and Tooling:


  • Development Lifecycle: Understand sandbox management and deployment strategies.
  • Version Control: Use Git for versioning and collaboration.
  • Salesforce CLI and VS Code: Leverage tools for development and automation.

  • 6. Data Management:


  • Data Loader: Perform bulk data operations and migrations.
  • Data Relationships: Manage relationships like lookup and master-detail.
  • Data Security: Implement sharing rules, profiles, and permission sets.

  • 7. Governance and Security:


  • Role Hierarchy and Sharing Rules: Control data access with hierarchy and rules.
  • Profiles and Permission Sets: Configure user permissions effectively.
  • Security Best Practices: Follow standards like OWASP Top 10 and CSRF.

  • 8. Advanced Topics: 


  • Lightning App Builder and Community Builder: Build custom applications and portals.
  • Einstein Analytics and AI: Integrate analytics and AI features.
  • Heroku Integration: Extend capabilities with custom applications.

  • 9. Industry-Specific Knowledge:

  • Salesforce Solutions: Understand industry-specific implementations.
  • Compliance and Regulations: Be aware of relevant regulations.

  • Focus on these areas to demonstrate your readiness and excel in your Salesforce Developer interview. Good luck!

    Create a Lightning Web Component (LWC) to display a list(10 Records) of contacts.

    Posted on TimeJune 24, 2024
        
            <template>
                <lightning-card title="Contact List">
                    <div class="slds-m-around_medium">
                        <template if:true={contacts}>
                            <ul class="slds-list_vertical">
                                <template for:each={contacts} for:item="contact">
                                    <li key={contact.Id}>{contact.Name}</li>
                                </template>
                            </ul>
                        </template>
                        <template if:false={contacts}>
                            <p>No contacts found.</p>
                        </template>
                    </div>
                </lightning-card>
            </template>
        
    
        
    
    import { LightningElement, wire } from 'lwc';
    import getContacts from '@salesforce/apex/ContactLWCController.getContacts';
    
    export default class ContactList extends LightningElement {
        contacts;
    
        @wire(getContacts)
        wiredContacts({ error, data }) {
            if (data) {
                this.contacts = data;
            } else if (error) {
                console.error('Error fetching contacts:', error);
            }
        }
    }
            
    
        
        
    
    public with sharing class ContactLWCController {
    	//@AuraEnabled annotation marks the Apex method as accessible to Lightning components (LWC, Aura components).
        @AuraEnabled(cacheable=true)
        public static List getContacts() {
            return [SELECT Id, Name FROM Contact LIMIT 10];
        }
    }
    
        

    Ensure certain field combinations are valid before a record is saved. For instance, if one field is True, ensure another field is not Null

    Posted on TimeJune 21, 2024

    Let’s consider the Account object for this scenario. Imagine we create two custom fields on the Account object:

    1. Has_Services__c (Checkbox): This field serves to indicate whether an account has active services associated with it.
    2. Service_Renewal_Date__c (Date): This field is designed to store the renewal date of the services linked to the account.

        
            
    trigger AccountTrigger on Account (before insert, before update) {
        if(Trigger.isBefore && (Trigger.isInsert || Trigger.isUpdate)) {
            AccountTriggerHandler.handleServices(trigger.new);
        } 
    }
            
        
        
    
    public class AccountTriggerHandler {
    	public static void handleServices(List newAccounts){
            for (Account acc : newAccounts) {
                // If Has_Services__c is true, ensure Service_Renewal_Date__c is not null
                if (acc.Has_Services__c && acc.Service_Renewal_Date__c == null) {
                    acc.addError('Please enter the Service Renewal Date for accounts with active services.');
                }
            }
        }
    }        
    
        
        
    
    @isTest
    private class AccountTriggerHandlerTest {
    	// Test method to cover scenario where Has_Services__c is true and Service_Renewal_Date__c is null
        @isTest
        static void testAccountWithServicesAndNullRenewalDate() {
            // Create a new Account with Has_Services__c true and Service_Renewal_Date__c as null
            Account acc = new Account(
                Name = 'Test Account',
                Has_Services__c = true
                // Service_Renewal_Date__c is intentionally left null
            );
    
            System.Test.startTest();
            try {
                insert acc;
                // If the validation is properly set up, this should throw an error
                System.assert(false, 'Expected validation rule to prevent saving with null Service_Renewal_Date__c');
            } catch (DmlException e) {
                // Ensure the correct error message is returned
                System.assertEquals('Please specify the Service Renewal Date.', e.getDmlMessage(0));
            }
            System.Test.stopTest();
        }
    
        // Test method to cover scenario where Has_Services__c is false and Service_Renewal_Date__c is null
        @isTest
        static void testAccountWithoutServicesAndNullRenewalDate() {
            // Create a new Account with Has_Services__c false and Service_Renewal_Date__c as null
            Account acc = new Account(
                Name = 'Test Account',
                Has_Services__c = false
                // Service_Renewal_Date__c is intentionally left null
            );
    
            System.Test.startTest();
            try {
                insert acc;
                // If the validation is properly set up, this should not throw an error
                System.assert(true);
            } catch (DmlException e) {
                // If an error occurs unexpectedly, fail the test
                System.assert(false, 'Unexpected error: ' + e.getDmlMessage(0));
            }
            System.Test.stopTest();
        }
    
    }
    
        

    When a parent record is deleted, delete all related child records.

    Posted on TimeJune 20, 2024

    Let's take Account and Contact object.

        
            
    trigger AccountTrigger on Account (after delete) {
        if(trigger.isAfter && trigger.isDelete) {
            AccountTriggerHandler.deleteRelatedContacts(trigger.old);
        }
    }
            
        
        
            
    public class AccountTriggerHandler {
        public static void deleteRelatedContacts(List oldAccounts) {
            // Collect all deleted accouts Id
            Set accIds = New Set();
            
            for(Account acc: oldAccounts){
                accIds.add(acc.Id);
            }
    
            if(!accIds.isEmpty()) {
                // Retrieve all related contact
                List relatedContacts = [SELECT Id FROM Contact WHERE AccountId IN: accIds];
                if(!relatedContacts.isEmpty()){
                    Delete relatedContacts;
                }
            }
        }
    }
            
        
        
            
    @isTest
    private class PracticeAccountTest {
        @isTest
        private static void testDeleteRelatedContacts() {
            Account testAccount1 = new Account(Name = 'Test Account 1');
            insert testAccount1;
            
            Contact testContact1 = new Contact(FirstName = 'John', LastName = 'Doe', AccountId = testAccount1.Id);
            insert testContact1;
    
            Account testAccount2 = new Account(Name = 'Test Account 2');
            insert testAccount2;
    
            Contact testContact2 = new Contact(FirstName = 'Jane', LastName = 'Smith', AccountId = testAccount2.Id);
            insert testContact2;
            
            List accountsToDeleteContacts = new List{testAccount1, testAccount2};
            List contactList = new List{testContact1, testContact2};
            System.Test.startTest();
            PracticeAccount.deleteRelatedContacts(accountsToDeleteContacts);
            System.Test.stopTest();
            
            List remainingContacts = [SELECT Id FROM Contact WHERE Id IN :contactList];
            System.assertEquals(0, remainingContacts.size(), 'Related Contacts should be deleted');
        }
    }
            
        

    When a case is inserted on any account put the latest case number on the account in latest case inserted field

    Posted on TimeJune 19, 2024
        
            
    trigger CaseTrigger on Case (after insert) {
        if(trigger.isAfter && trigger.isInsert) {
            CaseTriggerHandler.updateLatestCaseOnAccount(trigger.new);
        }
    }
            
        
        
            
    public class CaseTriggerHandler {
    
        public static void updateLatestCaseOnAccount(List newCases) {
            
            Set accIds = new Set();
            Map accMap = new Map();
            
            for(Case cs: newCases) {
                if(cs.AccountId != null) {
                	accIds.add(cs.AccountId);   
                }
            }
            
            if(!accIds.isEmpty()) {
                accMap = New Map([SELECT Id, Latest_Case_Inserted__c FROM Account WHERE Id IN:accIds]);
            }
    
            for(Case cs : newCases) {
                if(cs.AccountId != null && accMap.containsKey(cs.AccountId)) {
                    Account a = accMap.get(cs.AccountId);
                    a.Latest_Case_Inserted__c = cs.CaseNumber;
                }
            }
            
            if(!accMap.isEmpty()) {
            	update accMap.values();            
            }
        }
    }        
            
        
        
            
    @isTest
    private class CaseTriggerHandlerTest {
    
        @isTest
        static void testUpdateLatestCaseOnAccount() {
            // Create test data
            Account acc = new Account(Name = 'Test Account');
            insert acc;
    
            Case cs = new Case(
                AccountId = acc.Id,
                Subject = 'Test Case',
                Contact_Email__c = 'test@test.com'
            );
            insert cs;
    
            PracticeCaseTriggerHandler.updateLatestCaseOnAccount(new List{ cs });
    
            Account updatedAccount = [SELECT Id, Latest_Case_Inserted__c FROM Account WHERE Id = :acc.Id];
    
            System.assertEquals(cs.CaseNumber, updatedAccount.Latest_Case_Inserted__c,
                                'Latest_Case_Inserted__c field on Account should be updated correctly');
    
        }
    }        
            
        

    Whenever account's phone field is updated then all related contact's phone field should also get updated with the parent account's phone

        
            
    trigger AccountTrigger on Account (after update) {
        if (Trigger.isAfter && Trigger.isUpdate) {
            UpdateContactPhoneHandler.handleUpdate(Trigger.newMap, Trigger.oldMap);
        }
    }
            
        
        
            
    public class AccountTriggerHandler {
    	public static void updatePhoneField(Map newAccMap, Map oldAccMap) {
            
          	set accIds = new Set();
            List contactToBeUpdate = new List();
            
            for(Account acc: newAccMap.values()) {
                if(acc.Phone != oldAccMap.get(acc.Id).Phone) {
                    accIds.add(acc.Id);
                }
            }
            
            if (!accIds.isEmpty()) {
                List conList = [SELECT Id, Phone, AccountId 
                                         FROM Contact 
                                         WHERE AccountId IN: accIds];
                
                if(!conList.isEmpty()) {
                    for(Contact con: conList) {
                        con.Phone =  newAccMap.get(con.AccountId).Phone;
                        contactToBeUpdate.add(con);
                    }   
                }
            }
            
            if(!contactToBeUpdate.isEmpty()) {
                update contactToBeUpdate;
            }
        }
    }        
            
        
        
            
    @isTest
    private class AccountTriggerHandlerTest {
        @isTest
        static void testContactPhoneUpdate() {
            // Create test data
            Account acc = new Account(Name = 'Test Account', Phone = '123-456-7890');
            insert acc;
            
            Contact con = new Contact(FirstName = 'Test', LastName = 'Contact', AccountId = acc.Id);
            insert con;
            
            // Update the Account's phone number
            acc.Phone = '987-654-3210';
            update acc;
            
            // Retrieve the updated contact
            Contact updatedCon = [SELECT Id, Phone FROM Contact WHERE Id = :con.Id];
            
            // Assert that the contact's phone field got updated
            System.assertEquals(acc.Phone, updatedCon.Phone);
        }
    }        
            
        

    Write a trigger that prevents records from being deleted if a certain condition is met

    Posted on TimeJune 18, 2024
        
            
    trigger OppTrigger on Opportunity (before delete) {
        OppTriggerHandler.handleBeforeDelete(Trigger.old);
    }
            
        
        
            
    public class OppTriggerHandler {
        
        public static void handleBeforeDelete(List opportunities) {
            // Check if Opportunity Stage is 'Closed Won' and prevent deletion
            for (Opportunity opp : opportunities) {
                if (opp.StageName == 'Closed Won') {
                    opp.addError('Opportunity cannot be deleted because Stage is Closed Won.');
                }
            }
        }
    }        
            
        
        
            
    @isTest
    private class OppTriggerTest {
        
        static testMethod void testPreventOpportunityDeletion() {
            // Create test opportunities
            Opportunity opp1 = new Opportunity(
                Name = 'Test Opp 1',
                StageName = 'Prospecting',
                CloseDate = Date.today() + 30
            );
            Opportunity opp2 = new Opportunity(
                Name = 'Test Opp 2',
                StageName = 'Closed Won',
                CloseDate = Date.today() + 15
            );
            
            insert new List{opp1, opp2};
            
            System.Test.startTest();
            
            // Attempt to delete records
            try {
                delete new List{opp1, opp2};
            } catch (DmlException e) {
                String expectedMessage = 'Opportunity cannot be deleted because Stage is Closed Won.';
                System.assertEquals(expectedMessage, e.getDmlMessage(0));
            }
            
            System.Test.stopTest();
        }
    }
            
        

    Write a trigger that creates a related record (e.g., use Account & Contact Objects) after a new record is inserted

    Posted on TimeJune 17, 2024

    Let's take Account and Contact object.

        
            
    trigger AccountTrigger on Account (after insert) {
        if (Trigger.isInsert && Trigger.isAfter) {
            AccountTriggerHandler.createContacts(Trigger.new);
        }
    }
            
        
        
    
    public class AccountTriggerHandler {
    	public static void createContacts(List newAccounts) {
    		List contactsToCreate = new List();
    		
    		for (Account acc : newAccounts) {
    			Contact newContact = new Contact(
    				FirstName = 'First Name',
    				LastName = 'Last Name',
    				AccountId = acc.Id
    			);
    			contactsToCreate.add(newContact);
    		}
    		
    		if (!contactsToCreate.isEmpty()) {
    			insert contactsToCreate;
    		}
    	}
    }
    
        
        
    
    @isTest
    public class AccountTriggerHandlerTest {
    	
    	@isTest
    	static void testCreateContactAfterAccountInsert() {
    		// Test scenario where a single Account is inserted
    		
    		System.Test.startTest();
    		Account acc = new Account(Name = 'Test Account');
    		insert acc;
    		System.Test.stopTest();
    		
    		Contact createdContact = [SELECT Id, FirstName, LastName, AccountId FROM Contact WHERE AccountId = :acc.Id LIMIT 1];
    		
    		// Verify that a Contact was created and is associated with the Account
    		System.assertNotEquals(null, createdContact, 'Contact should be created');
    		System.assertEquals('First Name', createdContact.FirstName, 'First Name should be default');
    		System.assertEquals('Last Name', createdContact.LastName, 'Last Name should be default');
    		System.assertEquals(acc.Id, createdContact.AccountId, 'Contact should be related to the Account');
    	}
    
    	@isTest
    	static void testCreateContactsForMultipleAccounts() {
    		// Test scenario where multiple Accounts are inserted
    		
    		System.Test.startTest();
    		List accounts = new List();
    		for (Integer i = 0; i < 3; i++) {
    			accounts.add(new Account(Name = 'Test Account ' + i));
    		}
    		insert accounts;
    		System.Test.stopTest();
    
    		List createdContacts = [SELECT Id, FirstName, LastName, AccountId FROM Contact WHERE AccountId IN :accounts];
    		
    		// Verify that a Contact was created for each Account
    		System.assertEquals(3, createdContacts.size(), 'There should be 3 Contacts created');
    
    		for (Account acc : accounts) {
    			Boolean contactExists = false;
    			for (Contact con : createdContacts) {
    				if (con.AccountId == acc.Id) {
    					contactExists = true;
    					break;
    				}
    			}
    			System.assertEquals(true, contactExists, 'A Contact should be created for each Account');
    		}
    	}
    }
    
        

    Write a trigger that sets a default value for a field when a new record is inserted.

    Posted on TimeJune 12, 2024

    Trigger

    UI Development in Salesforce | UI Development in Lightning Experience

    Salesforce offers two ways to build user interfaces (UI) in Lightning Experience: low-code and pro-code.

    1. Use low-code point-and-click tools to implement business logic or build user interfaces.
    2. Use pro-code tools to write your own code and fully customize your apps.

     Low-code: 

    • Lightning pages
    • Quick actions
    • URL buttons
    • Utility bar
    • Flows

    Pro-code:

    • Lightning Web Components
    • Aura Components
    • Visualforce