SALESFORCE Interview Questions & Answers
SALESFORCE
Interview Questions & Answers
Consolidated Master Reference — Lead / Architect Track
Category-wise · De-duplicated · 9 source documents merged
Architecture & Design Patterns
12 questions
Q1. What is data skew in Salesforce?
record-locking and performance issues, Approval Process waiting for manager to approve the Quote.
Q2. What is a big object? Give an example of a standard big object.
A big object stores a massive amount of data. Example like Lead.
Q3. What is an Apex trigger framework, and what different trigger frameworks are available in Salesforce?
Trigger Handler pattern - an Apex class that handles the trigger logic.
Trigger framework using a virtual class - a base virtual handler class with overridable beforeInsert, afterUpdate.
Trigger framework using an interface - handlers implement a common interface, rarely use.
Q4. When should we use a trigger and when should we use declarative automation?
Use Salesforce Flow for most automation in Salesforce, and use an Apex trigger for complex logic that cannot be achieved with Flow like error handling and redirecting.
Q5. How do you handle large data volumes in Salesforce?
Use batch jobs (Batch Apex) and scheduled jobs to process records asynchronously.
Avoid use of custom fields, as they impact performance.
Use Change Data Capture for propagating changes.
Q6. How do you design a Salesforce architecture with a third-party application - what are the steps and phases?
Get answer from the SSIA doc.
Q7. What is a Data Warehouse?
A data warehouse is the concept of consolidating transaction data into a central store for analysis.
Q8. Do you have an exception handling framework? How does it work?
Asked at: Cognizant
Yes - we have a custom logging object, ACE_Exception_log__c, which stores the exception details.
Q9. How do you handle a one-time data migration of a huge number of records (lakhs of records)?
Asked at: Cognizant
Using (Data Loader or an ETL tool) Bulk API and processed with Batch Apex. use External IDs as match keys, load parents before children, deactivate triggers/workflows/validation rules during the load, load in parallel batches, then re-enable automation and reconcile counts.
Q10. What is a good set of naming conventions to use when developing on the Force.com platform?
Follow the CamelCase Java conventions.
Q11. What is MVC architecture in Salesforce?
Model - object creation.
View – LWC OR Visualforce page.
Controller - Apex controller contains the logic.
Integration - Concepts & Patterns
51 questions
Q13. How can Service Cloud be integrated with other Salesforce clouds or third-party applications?
Integration is achieved through the standard Salesforce integration mechanisms:
REST API and SOAP API for request/reply.
Middleware and integration platforms such as MuleSoft.
Q14. What are web services?
In integration terms, web services are the functionality or code that helps us to integrate. They are open-standard based (XML, JSON, SOAP, HTTP, REST, WSDL) web applications that interact with other web applications for the purpose of exchanging data.
Q15. Explain the Salesforce integration patterns.
Get answer from the SSIA doc.
Salesforce defines the following integration patterns:
Remote Process Invocation - Request and Reply: Salesforce invokes a process on a remote system, waits for the completion of that process, and then tracks state based on the response from the remote system.
Remote Process Invocation - Fire and Forget: Salesforce invokes a process in a remote system but doesn't wait for completion of the process. Instead, the remote process receives and acknowledges the request and then hands control back to Salesforce.
Batch Data Synchronization: data stored in the Lightning Platform is created or refreshed to reflect updates from an external system, and changes from the Lightning Platform are sent to an external system. Updates in either direction are done in a batch manner.
Remote Call-In: data stored in the Lightning Platform is created, retrieved, updated or deleted by a remote system.
UI Update Based on Data Changes: the Salesforce user interface must be automatically updated as a result of changes to Salesforce data.
Data Virtualization: Salesforce accesses external data in real time. This removes the need to persist data in Salesforce and then reconcile the data between Salesforce and the external system.
Q16. Describe a scenario where you integrated Salesforce Flow with external systems or services.
Answer supplied - source left blank.
A model answer, told as STAR:
Situation: Sales reps needed a real-time credit check from an external finance API before an Opportunity could move to the Contract stage.
Action: Registered the finance API as an External Service using its OpenAPI schema, with a Named Credential holding the endpoint and OAuth credentials so no secrets sat in the flow. Built a screen flow launched from a quick action that collected the customer reference, called the generated External Service action, and used a Decision on the returned credit rating to either update the Opportunity and advance the stage, or show the rep an error screen with the decline reason. A fault path logged failures to an Integration_Log__c object and notified the integration team.
Alternatives mentioned: for simpler REST calls, the HTTP Callout action in Flow Builder generates the action directly from a sample response; for complex transformation or protocols the flow instead calls an @InvocableMethod Apex class or publishes a Platform Event consumed by MuleSoft.
Result: Credit checks moved from a two-day email loop to seconds inside the sales process, with a full audit trail.
Q17. Can Salesforce Flow interact with external systems? If yes, how?
Yes Using an Apex action, a Flow can invoke an Apex class that performs HTTP requests to external web services, allowing data exchange between Salesforce and external systems. Use of @InvocableMethod annotation.
Q18. How does MuleSoft integrate with Salesforce?
Asked at: Cognizant
Answer supplied - source left blank.
MuleSoft integrates with Salesforce through the Anypoint Platform Salesforce Connector
Q19. How do REST services transfer data?
Data is transferred using the URL (endpoint/URI) and a JSON payload.
[] denotes an array
{} denotes an object
Q20. What are the important points to remember when writing an API in Salesforce?
A wrapper class with {get; set;} is only needed in Visualforce pages, not in an API class.
For a POST JSON request, use Map<String, String> or a wrapper class to read the values.
Bulkify the insert or update code - always work with a List.
Always send the request in JSON POST format.
Use Savepoint sp = Database.setSavepoint(); and Database.rollback(sp); in the catch block to roll back if an error occurs.
Use Database.upsert() to allow partial record processing.
Always set the response body, whether the call fails or passes.
API limits: Professional and Enterprise editions can have around 250,000 calls (2.5 lakh) per 24 hours, or contact Salesforce to increase it.
@ReadOnly doubles the query row limit to 1,000,000 rows.
Q21. What are the HTTP resource method annotations in Apex REST?
@HttpGet - select
@HttpPut - insert
@HttpPost - upsert
@HttpPatch - update
@HttpDelete - delete
Q22. What are RestRequest, RestContext, and @RestResource(urlMapping)?
RestRequest: the object that stores the incoming REST request.
RestContext: used to access the current REST request and response.
@RestResource: the annotation used to specify a resource and make the class global so it is exposed outside Salesforce. Mentioning the path is mandatory for REST services.
The URI takes the form /services/apexrest/RestAllCases/.
RestRequest req = RestContext.request; // get the current REST request
Q23. Explain the use of an outbound message.
automation action that can fire from a workflow rule (or an approval process). It sends a SOAP message to an external web service endpoint containing the field values you specify, which can subsequently kick off additional processes in the external system. It is declarative, retries automatically on failure, and can include a session Id so the external system can call back into Salesforce.
Q24. What is OAuth?
used as a way to grant websites or applications access to information on other websites without giving them the passwords. In Salesforce it is used by Connected Apps, and there are several flows - Web Server, User-Agent, JWT Bearer, Username-Password, Refresh Token and Device flow.
Q25. What is a Connected App?
A connected app integrates an application with Salesforce using APIs. Connected apps use standard SAML and OAuth protocols to authenticate, provide single sign-on and provide tokens for use with Salesforce APIs. In addition to standard OAuth capabilities, connected apps allow Salesforce admins to set various security policies and have explicit control over who can use the corresponding apps (permitted users, IP relaxation, refresh token policy).
Q26. Can you give an example of a Salesforce API and its usage?
Salesforce has a variety of APIs that let you interact with the system in different ways:
REST API - lets you integrate with Force.com applications using simple HTTP methods in either XML or JSON format, making it ideal for developing mobile applications or external clients.
Bulk API - provides programmatic access that lets you quickly load large volumes of data into your Salesforce organisation (asynchronous, batched).
Streaming API - used to receive notifications for changes to Salesforce data that match a SOQL query you define. It is useful when you want notifications to be pushed from the server to the client based on criteria you define.
(Others include SOAP API, Metadata API, Tooling API, Chatter REST API, Analytics API and the Connect API.)
Q27. What is a use case for Salesforce Connect?
Salesforce Connect is a product that uses external objects. External objects let you integrate information into Salesforce in real time without consuming Salesforce storage limits - the data stays in the external system and is fetched on demand via OData or a custom Apex adapter.
An example use case is integrating a large database that houses transaction history against an Account: the history is viewable and reportable in Salesforce but without using the large amount of storage it would otherwise require.
Q28. How do you perform bulk data migration with a third-party data migration tool?
Using Data Loader (or an equivalent bulk-capable tool), which uses the Bulk API to insert, update, upsert, delete, and export large volumes of records.
Q29. What is the difference between Named Credentials and Remote Site Settings?
Named Credentials: store the endpoint URL, (usernames, passwords, OAuth tokens) for external services.
Remote Site Settings: whitelist external websites so that Salesforce is permitted to make a callout to them.
Q30. What do the common HTTP status codes returned by a REST API mean?
1xx Informational
100 Continue: the client should continue with its request. This interim response indicates that everything so far is OK.
2xx Success
200 OK: the request was successful and the server returned the requested data.
201 Created: the request was successful and a new resource was created as a result.
204 No Content: the server successfully processed the request but there is no content to return.
3xx Redirection
301 Moved Permanently: the requested resource has been permanently moved to a new location.
302 Found (Moved Temporarily): the requested resource has been temporarily moved to a different location.
304 Not Modified: the client's cached copy is still valid and the server has not modified the requested resource.
4xx Client Errors
400 Bad Request: the request could not be understood or was missing required parameters.
401 Unauthorized: authentication is required and the provided credentials were not valid.
403 Forbidden: the server understood the request but refuses to authorize it.
404 Not Found: the requested resource could not be found on the server.
429 Too Many Requests: the user has sent too many requests in a given amount of time (rate limiting).
5xx Server Errors
500 Internal Server Error: a generic error returned when an unexpected condition was encountered on the server.
502 Bad Gateway: the server was acting as a gateway or proxy and received an invalid response from the upstream server.
503 Service Unavailable: the server is not ready to handle the request - commonly down for maintenance or overloaded.
504 Gateway Timeout: the server was acting as a gateway or proxy and did not receive a timely response from the upstream server.
Q31. What is data mapping?
Is a process of mapping source fields to target fields formats.
Q32. What is data cleansing?
Is a process of removing a duplicate, inaccurate data from the system.
Q33. What challenges do you face during the integration process or data migration with a third-party application?
Data issues and their datatype formats source to destination.
Q34. Have you worked on Platform Events? What are they?
Asked at: GenPact
Answer get from SSIA Doc.
Q35. Have you worked on REST APIs?
Asked at: GenPact
Yes - REST.
Inbound: expose Apex as a REST resource with @RestResource(urlMapping='/...') and the @HttpGet, @HttpPost, @HttpPut, @HttpPatch, @HttpDelete annotations.
Outbound: call an external REST service with HttpRequest/Http, setting the endpoint, method, headers and body, and authenticate with a Named Credential.
Q36. How do you call an external web service from Salesforce?
Asked at: Accenture, GenPact
Build an HttpRequest, set the endpoint, method and body, then send it with Http.send():
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:My_Named_Credential/services/data/v58.0/sobjects/Account');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(payload));
HttpResponse res = http.send(req);
The remote site must be registered in Remote Site Settings, or accessed through a Named Credential.
Callouts are not allowed from a trigger unless made asynchronously (@future(callout=true) or Queueable with Database.AllowsCallouts).
Q37. How will you handle a huge volume of data in an integration?
Asked at: Cognizant
Use Big Objects to store very large volumes of data without consuming standard data storage, and Batch Apex to process it in chunks.
Use the Bulk API (asynchronous, batched) rather than SOAP/REST row-by-row calls.
MuleSoft is used as the integration/ETL layer to move and transform the data.
Consider Salesforce Connect / external objects when the data only needs to be viewed, not stored.
Q38. Why would you use MuleSoft instead of Heroku - what is the difference?
Asked at: Cognizant
MuleSoft provides more integration features than Heroku - message routing, JDBC connectivity, and a Java-based ESB (Enterprise Service Bus) with out-of-the-box connectors, transformation (DataWeave) and API management. Heroku is a PaaS for building and hosting custom applications, not an integration platform; you would have to write the integration logic yourself.
Q39. When should you use a platform event?
Asked at: Cloud 360
Answer supplied - source left blank.
Use a platform event when systems (or parts of one system) must be decoupled and communicate asynchronously:
Broadcasting a change to many subscribers at once (one publish, many listeners) instead of point-to-point integration.
Near-real-time outbound integration - notifying an external system without holding the Salesforce transaction open (unlike a callout, the publish is not a callout).
Inbound integration - an external system publishes an event and Salesforce reacts in an Apex trigger or Flow.
Decoupling internal logic - firing an event from a trigger so long-running processing happens in its own transaction with fresh governor limits.
When you need replay/durability (events are retained 24-72 hours and can be replayed by ReplayId).
Do not use them when you need a synchronous response or a guaranteed ordered request/reply - use REST/SOAP callouts for that.
Also noted:
Component events follow the parent-to-child or child-to-parent relationship, whereas application events are used to communicate between components that are not directly related in the hierarchy.
Component events follow a bubbling or capturing phase within the component hierarchy, whereas application events propagate throughout the entire Lightning application.
They follow an event-driven architecture based on a publish-subscribe model.
Publishers publish event messages to the event bus (Apex EventBus.publish(), Flow, Process Builder, or an external system via the API); subscribers (Apex triggers, Flows, Lightning components with empApi, external CometD clients) receive them asynchronously.
Publisher and subscriber are decoupled - neither needs to know about the other.
Q40. What is SOAP?
SOAP stands for Simple Object Access Protocol. It is a protocol that defines a uniform way of passing XML-encoded data.
Q41. Can report data be accessed programmatically?
Yes. As of Winter '14, the Analytics REST API is generally available (it was introduced as a limited pilot in Summer '13). The Analytics API lets you integrate Salesforce report data into your apps programmatically and has several resources that let you query metadata and record details.
Q42. What is an API in Salesforce and how can we use it?
Salesforce has a set of APIs to access data from Force.com or Database.com:
SOAP API - is a process of XML format data at enterprise level, simple object access protocol.
REST API - 3rd party external application data sync single record of change not in bulk records. Data transfer in most Json format or XML.
Bulk API - an asynchronous API able to manage large sets of data. BATCH APEX, QUEUEABLE ETC
Streaming API - allows you to create a PushTopic based on a query and get updates as the query results change. It is used when notifications must be pushed based on defined criteria.
Q43. How many callouts to an external service can be made in a single Apex transaction?
Callout per Apex transaction - 100
Maximum timeout period callout - 120 seconds
Q44. What is the maximum allowed time limit when making a callout to an external service in Apex?
A maximum cumulative timeout of 120 seconds is enforced for all callouts in a transaction.
Q45. How can you expose an Apex class as a REST web service in Salesforce?
An Apex class can be exposed as a REST web service by annotating it with @RestResource.
@RestResource(urlMapping='/MyService/*')
global with sharing class MyService { }
Q46. What is the default timeout of callouts (HTTP requests) in a transaction?
The default timeout for callouts is 10 seconds.
Q47. When is an @HttpPut annotated method called in REST?
The @HttpPut method is called when a PUT request is sent; PUT creates the record if it does not exist and updates it (upsert) if it does.
Q48. What is a WSDL, and what is the difference between the Enterprise and Partner WSDL?
WSDL stands for Web Services Description Language. It is an XML document that describes how an external program can communicate with Salesforce - the public interface of the web service, the protocol used to exchange information (SOAP), the location (endpoint) of the service, and the methods it exposes. Client applications need it to understand what the web service actually does.
Salesforce provides two WSDL files for API access:
Enterprise WSDL - all fields are declared in each object, so it is a direct, strongly typed map of your current org schema. It must be regenerated when the schema changes.
Partner WSDL - objects and fields are discoverable through introspection, so the client determines the schema as needed. It is loosely typed and suits tools that work against many orgs.
The main WSDL elements are definitions, targetNamespace, types (data types), message (the messages to exchange), portType, binding and service. A specific port and URL are assigned, and only the methods listed in the WSDL are exposed to the client.
The direction of the flow is Salesforce -> WSDL -> external system consumes the WSDL, that is, provider to consumer.
Q49. How do you consume an external SOAP web service from Apex?
Generate the Apex stubs from the WSDL: Setup > Apex Classes > Generate from WSDL (WSDL2Apex). Parsing produces both synchronous and asynchronous classes, plus the types and return types for all the operations in the WSDL.
The chain is: WSDL2Apex -> Async or Sync classes -> Types + Return Types.
Before calling any external service you must authorise the endpoint: Setup > Remote Site Settings > New Remote Site, and add the endpoint URL. The <soap:address location="URL"> element in the WSDL gives you the endpoint address.
Call the generated stub's method, passing the generated request types, and read the generated response type.
Named Credentials are the modern alternative to Remote Site Settings when authentication is involved, because they store the endpoint and the credentials together.
Q50. Why do you need Remote Site Settings, and how do you configure one?
Whitelist the external urls in Salesforce so easily data transaction cancelled be performed. Setup > remote site settings.
Q51. Write Apex code that performs a GET callout to an external REST service and parses the JSON response.
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('GET');
HttpResponse response = http.send(request);
// If the request is successful, parse the JSON response.
if (response.getStatusCode() == 200) {
// Deserialize the JSON string into collections of primitive data types.
Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
// Cast the values in the 'animals' key as a list
List<Object> animals = (List<Object>) results.get('animals');
System.debug('Received the following animals:');
for (Object animal : animals) {
System.debug(animal);
}
}
JSON.deserializeUntyped() is used when you do not have (or do not want) an Apex class matching the payload; use JSON.deserialize(body, MyWrapper.class) when you do. Remember to register the endpoint in Remote Site Settings first.
Q52. Write Apex code that sends a JSON body to an external REST service with a POST callout.
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json;charset=UTF-8');
// Set the body as a JSON object
request.setBody('{"name":"mighty moose"}');
HttpResponse response = http.send(request);
// Parse the JSON response
if (response.getStatusCode() != 201) {
System.debug('The status code returned was not expected: ' +
response.getStatusCode() + ' ' + response.getStatus());
} else {
System.debug(response.getBody());
}
In production, build the body with JSON.serialize(myWrapper) rather than concatenating strings, and wrap the callout in try/catch.
Q53. Write an Apex integration class that pushes a list of Leads to an external CTI system and records the outcome on each Lead.
The service class builds a wrapper, serializes it, posts it, then interprets the vendor's response code and writes an integration tracker record.
public class CTILeadUploadIntegration {
public static Boolean triggerExecutute = true; // changes also done in SS_IntegrationTrigger
public static void UploadLeadCTI(List<Lead> QueryListLead) {
String url = 'http://59.160.171.123:8081/LeadUploadCTI/api/UploadCTIData';
CTILeadUploadRequest restReq = new CTILeadUploadRequest();
for (Lead ld : QueryListLead) {
CTILeadUploadRequest.LeadWrapper LeadWrap = new CTILeadUploadRequest.LeadWrapper();
LeadWrap.LEADID = ld.Id;
LeadWrap.Customer_Name = ld.Name;
LeadWrap.Mobile = ld.Mobile__c;
LeadWrap.LeadSource = ld.LeadSource;
LeadWrap.LeadStage = ld.Lead_Stage__c;
LeadWrap.SOURCE = ld.utm_source__c;
LeadWrap.Extra1 = ld.States__c;
LeadWrap.Extra2 = ld.Dialer_Priortization__c;
LeadWrap.Extra3 = '';
LeadWrap.Extra4 = '';
LeadWrap.Extra5 = '';
restReq.Leads.add(LeadWrap);
}
triggerExecutute = false;
Integration_Tracker__c trac = new Integration_Tracker__c();
HttpRequest Request = new HttpRequest();
Request.setEndpoint(Label.CTILeadIntegrationEndPoint);
Request.setMethod('POST');
Request.setHeader('Content-Type', 'application/json');
Request.setHeader('Accept', 'application/json');
Request.setBody(JSON.serialize(restReq));
trac.JSON__c = JSON.serialize(restReq);
trac.Object__c = 'Lead';
Http http = new Http();
HttpResponse Response = http.send(Request);
System.debug('Response@@' + Response);
if (Response.getStatusCode() == 200) {
Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(Response.getBody());
if ((String) results.get('ResponseCode') == '00') {
CTILeadUploadResponse RestResponse =
(CTILeadUploadResponse) JSON.deserialize(Response.getBody(), CTILeadUploadResponse.class);
for (Lead leadstatusUpdate : QueryListLead) {
leadstatusUpdate.CTI_Status__c = '00';
}
update QueryListLead;
} else if ((String) results.get('ResponseCode') == '02') {
CTILeadUploadResponse RestResponse =
(CTILeadUploadResponse) JSON.deserialize(Response.getBody(), CTILeadUploadResponse.class);
for (CTILeadUploadResponse.DataNotAddedWrapper DatanotWrap : RestResponse.DataResult.DataNotAdded) {
for (Lead leadpartial : QueryListLead) {
if (leadpartial.Id == DatanotWrap.record_id) {
leadpartial.CTI_Status__c = '02';
} else {
leadpartial.CTI_Status__c = '00';
}
}
}
update QueryListLead;
} else if ((String) results.get('ResponseCode') == '01') {
CTILeadUploadErrorResponse restErrorResponse =
(CTILeadUploadErrorResponse) JSON.deserialize(Response.getBody(), CTILeadUploadErrorResponse.class);
for (Lead leadError : QueryListLead) {
leadError.CTI_Status__c = '01';
}
update QueryListLead;
}
}
trac.Response_Body__c = Response.getBody();
trac.Response_Code__c = Response.getStatusCode();
trac.Object__c = 'Lead';
insert trac;
}
}
The request wrapper that is serialized into the body:
public class CTILeadUploadRequest {
public List<LeadWrapper> Leads;
public CTILeadUploadRequest() {
Leads = new List<LeadWrapper>();
}
public class LeadWrapper {
public String LEADID;
public String Customer_Name;
public String Mobile;
public String LeadSource;
public String LeadStage;
public String LeadPriority;
public String SOURCE;
public String Extra1;
public String Extra2;
public String Extra3;
public String Extra4;
public String Extra5;
public LeadWrapper() {
LEADID = '';
Customer_Name = '';
Mobile = '';
LeadSource = '';
LeadStage = '';
LeadPriority = '';
SOURCE = '';
Extra1 = '';
Extra2 = '';
Extra3 = '';
Extra4 = '';
Extra5 = '';
}
}
}
Note the endpoint is held in a custom label so it can be changed per environment, a static flag prevents the trigger from re-entering during the update, and every call is logged to an Integration_Tracker__c record for support. If this is invoked from a trigger the method must be made asynchronous (@future(callout=true) or Queueable).
Q54. Which annotations do you use to expose an Apex class as a REST resource, and how do you read the incoming request?
@RestResource(urlMapping='/RestAllCases/*') is the class-level annotation that specifies the resource and makes it global so it is exposed outside Salesforce. The class must be global, and the URI always starts with /services/apexrest/ - for example /services/apexrest/RestAllCases/.
Method annotations map to HTTP verbs, and each may appear only once per class:
@HttpGet - retrieve records (select).
@HttpPost - create records (also used for insert/upsert style operations).
@HttpPut - insert or replace the record.
@HttpPatch - update the record.
@HttpDelete - delete records.
RestContext gives access to the current request and response: RestRequest req = RestContext.request; and RestContext.response.
RestRequest stores the incoming request - requestBody, params, headers, requestURI.
Write the response with RestContext.response.addHeader('Content-Type','application/json'); and RestContext.response.responseBody = Blob.valueOf(jsonStr);.
REST in Salesforce is stateless, works over URLs, and supports both XML and JSON, with JSON as the default representation.
Q55. How do you expose a custom REST API endpoint in Apex that accepts a JSON date range in the POST body and returns matching records?
@RestResource(urlMapping='/PayoutBillDates/*')
global with sharing class PayoutBillDateRest {
@HttpPost
global static void getPayouts() {
try {
RestRequest request = RestContext.request;
if (String.isNotBlank(request.requestBody.toString())) {
RequestBodyWrapper requestBody =
(RequestBodyWrapper) JSON.deserialize(request.requestBody.toString(), RequestBodyWrapper.class);
List<Payout__c> payoutlst = [SELECT Name, Patient_Name__c, Max_ID__c, Transaction_Type__c, IPID__c,
alletec_hospitallocation__r.Name, Doctor__r.Name,
alletec_speciality__r.Name, HCF_Source__r.Name, Parent_Account__c,
New_Pre_Intimation_Date_Time__c, Patient_Reg_DateTime__c,
alletec_dateofadmission__c, Date_Time_of_Admission__c,
Date_of_Discharge__c, Pre_Intimation_Status__c, SMS_Tagged__c,
Auto_Tagged__c, First_OPD_IPD_Bill_Date__c, First_OPD_IPD_Bill_No__c,
Tagged_On__c, Remarks__c, Message_Description__c, Nationality__c,
pcl_markuppercentage__c, invoicenumber__c, alletec_hisamount__c,
Discount__c, OPID__c, Number_of_Hours__c, Payout_Percentage__c,
GST__c, Total_Payout__c, alletec_billdate__c
FROM Payout__c
WHERE alletec_billdate__c >= :requestBody.startDate
AND alletec_billdate__c <= :requestBody.endDate
ORDER BY alletec_billdate__c DESC
LIMIT 50000];
String records = '[';
for (Payout__c pay : payoutlst) {
records += '{"Patient Name":"' + pay.Name + '","Max Id":"' + pay.Max_ID__c + '","Transaction Type":"' + pay.Transaction_Type__c + '"';
if (pay.New_Pre_Intimation_Date_Time__c != null)
records += ',"New Pre Intimation Date Time":"' + pay.New_Pre_Intimation_Date_Time__c.format() + '"';
if (pay.Patient_Reg_DateTime__c != null)
records += ',"Patient Reg DateTime":"' + pay.Patient_Reg_DateTime__c.format() + '"';
records += ',"Total Amount":"' + pay.alletec_hisamount__c + '","Payout percent":"' + pay.Payout_Percentage__c +
'","GST":"' + pay.GST__c + '","Total Payout":"' + pay.Total_Payout__c +
'","Bill Date":"' + pay.alletec_billdate__c.format() + '"},';
}
if (records.contains(','))
records = records.removeEnd(',');
records += ']';
String jsonStr = '{"success" : true,"PayoutList" : "' + records + '"}';
RestContext.response.addHeader('Content-Type', 'application/json');
RestContext.response.responseBody = Blob.valueOf(jsonStr);
return;
} else {
String jsonStr = '{"success" : false,"message" : "Provide Body"}';
RestContext.response.addHeader('Content-Type', 'application/json');
RestContext.response.responseBody = Blob.valueOf(jsonStr);
return;
}
} catch (Exception e) {
String jsonStr = '{"success" : false,"message" : "' + e.getMessage() + '"}';
RestContext.response.addHeader('Content-Type', 'application/json');
RestContext.response.responseBody = Blob.valueOf(jsonStr);
return;
}
}
public class RequestBodyWrapper {
public Date startDate { get; set; }
public Date endDate { get; set; }
}
}
Key points: the class is global with sharing, the body is deserialized into an inner wrapper class, the blank-body case and the exception case both return a JSON response (always set a response body whether the call passes or fails), and the whole method is wrapped in try/catch. In real code prefer JSON.serialize() over hand-built JSON strings.
Q56. How do you expose a custom REST API endpoint in Apex that accepts an inbound invoice payload, inserts the records, logs partial failures and rolls back on error?
@RestResource(urlMapping='/InvoiceCreateAPI/*')
global with sharing class InvoiceCreateAPI {
@HttpPost
global static void createInvoice() {
Savepoint sp = Database.setSavepoint();
try {
RestRequest request = RestContext.request;
if (String.isNotBlank(request.requestBody.toString())) {
List<RequestBodyWrapper> requestBody =
(List<RequestBodyWrapper>) JSON.deserialize(request.requestBody.toString(), List<RequestBodyWrapper>.class);
Set<Id> jobrefidset = new Set<Id>(); // to store job reference ids
if (requestBody != null && requestBody.size() > 0) {
List<AM_Invoice__c> invoice2insertlst = new List<AM_Invoice__c>();
for (Integer i = 0; i < requestBody.size(); i++) {
AM_Invoice__c aic = new AM_Invoice__c();
aic.Job_Reference__c = requestBody[i].JobReferenceID;
aic.Name = requestBody[i].InvoiceID;
aic.Billing_Party__c = requestBody[i].AccountName;
aic.Invoice_Date__c = requestBody[i].InvoiceDate;
aic.Job_Sub_Total__c = requestBody[i].JobSubTotal;
aic.Invoice_Amount__c = requestBody[i].InvoiceTotalAmount;
aic.Revenue__c = requestBody[i].Revenue;
aic.invoice_pdf_link__c = requestBody[i].invoicepdflink;
if (!jobrefidset.contains(requestBody[i].JobReferenceID))
jobrefidset.add(requestBody[i].JobReferenceID);
invoice2insertlst.add(aic);
}
Map<Id, Job_Reference__c> mapId2jobref = new Map<Id, Job_Reference__c>(
[SELECT Id, Status__c, Opportunity__c FROM Job_Reference__c WHERE Id IN :jobrefidset]);
for (AM_Invoice__c invo : invoice2insertlst) {
if (mapId2jobref.containsKey(invo.Job_Reference__c))
invo.Opportunity__c = mapId2jobref.get(invo.Job_Reference__c).Opportunity__c;
}
if (invoice2insertlst != null && invoice2insertlst.size() > 0) {
Database.SaveResult[] resultList = Database.insert(invoice2insertlst, false);
List<API_Error_Log__c> listApiErrorLog = new List<API_Error_Log__c>();
for (Integer i = 0; i < resultList.size(); i++) {
if (!resultList[i].isSuccess()) {
API_Error_Log__c apiError = new API_Error_Log__c();
apiError.API_Name__c = 'createInvoice';
apiError.Error_Message__c = String.valueOf(resultList[i].getErrors());
apiError.Trigger_Point__c = 'Invoice Inserting';
listApiErrorLog.add(apiError);
}
}
List<Job_Reference__c> jobref2update = new List<Job_Reference__c>(); // to update Job Reference
jobrefidset.clear();
for (AM_Invoice__c aw : invoice2insertlst) {
if (aw.Id != null && !jobrefidset.contains(aw.Job_Reference__c)) {
if (mapId2jobref.containsKey(aw.Job_Reference__c)
&& mapId2jobref.get(aw.Job_Reference__c).Status__c != 'Invoiced') {
jobref2update.add(new Job_Reference__c(Id = aw.Job_Reference__c, Status__c = 'Invoiced'));
jobrefidset.add(aw.Job_Reference__c);
}
}
}
if (jobref2update != null && jobref2update.size() > 0)
update jobref2update;
if (listApiErrorLog != null && listApiErrorLog.size() > 0)
insert listApiErrorLog;
String jsonStr = '{"success" : true,"message" : "Invoice created Successfully."}';
RestContext.response.addHeader('Content-Type', 'application/json');
RestContext.response.responseBody = Blob.valueOf(jsonStr);
return;
}
}
} else {
String jsonStr = '{"success":"false","message":"Provide Body"}';
RestContext.response.addHeader('Content-Type', 'application/json');
RestContext.response.responseBody = Blob.valueOf(jsonStr);
return;
}
} catch (Exception e) {
Database.rollback(sp);
String jsonStr = '{"success" : false,"message" : " ' + e.getMessage() + '"}';
RestContext.response.addHeader('Content-Type', 'application/json');
RestContext.response.responseBody = Blob.valueOf(jsonStr);
return;
}
}
public class RequestBodyWrapper {
public String JobReferenceID;
public String InvoiceID;
public String AccountName;
public Date InvoiceDate;
public Integer JobSubTotal;
public Decimal InvoiceTotalAmount;
public Decimal Revenue;
public String invoicepdflink;
public String JobReference;
}
}
Techniques being demonstrated: Database.setSavepoint() with Database.rollback(sp) in the catch block, Database.insert(list, false) for partial success, writing each failure to an API_Error_Log__c custom object, bulkified list-based DML, a single map query for the parent records, and a JSON response body in every path.
Q57. What are the good practices to follow when writing an inbound Apex REST API in Salesforce?
Wrapper classes with {get; set;} properties are needed for Visualforce; for an API a plain wrapper with public members is enough.
To read a POST JSON request, deserialize into a Map<String, String> or, better, into a wrapper class.
Bulkify all inserts and updates - always build a List and do the DML once.
Always send the request in JSON POST format.
Use Savepoint sp = Database.setSavepoint(); and Database.rollback(sp); in the catch block so a partial failure does not leave inconsistent data.
Use Database.insert(records, false) / Database.upsert() when you want partial success, and log the failures (for example to an API_Error_Log__c object).
Always set a response body, on both the failure and the success path, and always put the logic inside try/catch.
Watch the API limits - Professional and Enterprise editions get a fixed daily API limit (around 250,000 calls) unless you buy more, and only 100 callouts are allowed in a single Apex transaction.
@ReadOnly doubles the query rows limit (to 1,000,000) for read-only endpoints.
Related limits worth quoting: Messaging.sendEmail can be invoked 10 times per transaction, 5,000 single emails per day (raisable by contacting Salesforce), and 225,000 workflow emails per day - so avoid sending email from code where you can.
Test the endpoint from Workbench (REST Explorer) or Postman.
Q58. How can a trigger make a callout to an external service?
A trigger cannot make a callout inline - the callout must not block the trigger process while it waits for a response. For a trigger to make a callout, the method containing the callout code must be annotated with @future(callout=true) so it runs on a separate thread, or it must be enqueued as a Queueable job that implements Database.AllowsCallouts.
Practical points:
Pass only primitives or collections of primitives to the future method (record Ids as Strings), and re-query the records inside it.
Guard against recursion with a static Boolean when the callout result updates the same records.
Bulkify: gather the Ids in the trigger and make one async call, not one per record.
Q59. What is the difference between REST API and SOAP API in Salesforce, and when do you use each?
SOAP API:
Works over HTTP using a WSDL file. It operates at the application layer of the TCP/IP stack (along with FTP, HTTP, POP, SNMP).
Lets you query and search data; create, update and delete data; work with approval processes; perform administrative tasks; and create and update sharing records.
The web service exposes standard Salesforce sObjects, including any custom fields.
Strongly typed and XML-only; use it for formal, contract-driven integrations, for legacy or enterprise middleware, and when you need the Enterprise WSDL's strict typing.
REST API:
Works over HTTP using URLs; the resources are addressed by URI. It was defined by Roy Fielding in 2000.
Stateless - the server holds no session between calls.
Supports both XML and JSON, with JSON as the default; data is normally returned as JSON.
Methods: GET (retrieve), POST (create), PATCH (update particular fields), PUT (insert or replace), DELETE, HEAD (get only the response header).
Lighter weight; use it for mobile and web clients, for lightweight integrations and where JSON is preferred.
In both directions the vocabulary is the same: exposing means Salesforce is the provider, consuming means Salesforce calls the other system. For authentication with an external API you normally need a username, password, client id and client secret (consumer key). A mock class holds the canned response used when testing the calls.
Q60. In how many ways can a JWT token be passed when calling a REST API?
Two ways are normally used.
1. In the request header, as a bearer token - this is the recommended approach:
GET /api/endpoint HTTP/1.1
Host: example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
2. As a request parameter, either in the query string or in the body:
GET /api/endpoint?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... HTTP/1.1
Host: example.com
POST /api/endpoint HTTP/1.1
Host: example.com
Content-Type: application/json
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
The header approach is preferred because query-string tokens end up in server logs, browser history and referrer headers. In Salesforce, the JWT bearer flow is used for server-to-server integration where no user interaction is possible: you sign a JWT with the certificate registered on the connected app, POST it to /services/oauth2/token with grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer, and receive an access token plus the instance URL.
Q61. What is Change Data Capture, and how do you subscribe to change events?
Change Data Capture (CDC) publishes changes from Salesforce to an external system in near real time.
It covers the create, update, delete and undelete operations.
It is used for data-capture integration in place of polling REST callouts, and can also be implemented alongside triggers (Apex change event triggers).
CDC requires an integration app on the other side that receives the events and performs the updates in the external system.
Salesforce stores change events for up to 3 days, so an app that goes offline can retrieve missed notifications.
Streaming events in general:
Streaming events are instant notification messages that one system (the publisher) sends to another (the subscriber).
With push technology the publisher pushes data to the subscriber; with pull technology clients request data from the server periodically.
Using the publish/subscribe model and push technology, CDC sends notifications to subscribers whenever a data change occurs in Salesforce.
Event-driven systems streamline communication between distributed enterprise systems, increase scalability and deliver real-time data.
Channels to subscribe to:
Subscribe to change events for Channel Example
--- --- ---
All objects /data/ChangeEvents N/A
A standard object /data/<Standard_Object_Name>ChangeEvent For accounts: /data/AccountChangeEvent
A custom object /data/<Custom_Object_Name>__ChangeEvent For Employee__c: /data/Employee__ChangeEvent
Required permissions:
/data/ChangeEvents - View All Data AND View All Users.
/data/UserChangeEvent - View All Users.
/data/<Object>ChangeEvent - View All for that object, OR View All Data. Some standard objects, such as Task and Event, have no View All permission, so View All Data is required.
Q62. How do you connect Postman to Salesforce and insert a record through the REST API?
1. Get an access token: send a POST to https://test.salesforce.com/services/oauth2/token (use login.salesforce.com for production) with five body parameters - username, password (password + security token), client_id, client_secret, grant_type=password.
2. The response contains both the access_token and the instance_url - always take the instance URL from the response rather than assuming it.
3. Build the request URL from the instance URL, for example <instance_url>/services/apexrest/InvoiceCreateAPI/ for a custom Apex REST class, or <instance_url>/services/data/v58.0/sobjects/Account/ for the standard API.
4. In the Authorization tab, choose type Bearer Token and paste the access token.
5. Put the JSON payload in the Body (raw, JSON) and send.
6. To update a record by external Id, send a PATCH to <instance_url>/services/data/vXX.X/sobjects/Object__c/External_Id_Field__c/<value> with the fields to update in the JSON body; each JSON key must be the API name of the field.
Useful Postman concepts:
Collection - a group of API requests stored and saved in a logical arrangement; collections are the basis for the advanced features.
Variables - defined at collection level and referenced as {{variable}}; global variables can be set in settings.
Environment - separate sets of variables per project or per org (sandbox, production).
Pre-request Script - JavaScript that runs before the request is sent (for example to fetch a fresh token).
Tests tab - JavaScript that runs after the response is received; output appears in the Postman console.
Q63. Universal Containers is building an integration between Salesforce and their data warehouse. Users need full CRUD access to warehouse data without leaving the Salesforce UI, and the integration must keep the same look and feel as the existing Salesforce interface. What should the architect recommend?
Answer supplied - the source dump had the options corrupted.
Use Salesforce Connect with External Objects.
Salesforce Connect surfaces data that lives in the external system as external objects, using an OData 2.0/4.0 adapter or a custom Apex Connector Framework adapter.
The data is read on demand at query time - nothing is copied into Salesforce, so there is no storage cost and no synchronisation job to maintain.
External objects behave like standard objects in the UI: list views, record detail pages, Lightning pages, reports and SOQL all work, which is what satisfies the "same look and feel" requirement.
Writeable external objects give the full create, read, update and delete capability the requirement asks for.
Indirect and external lookup relationships let you relate external objects to standard Salesforce records.
Why the alternatives do not fit: an ETL or Bulk API load copies the data (storage cost, staleness); a Visualforce or Canvas embed of the warehouse UI would not match the Salesforce look and feel; Apex callouts alone would mean building the entire CRUD interface by hand.
Security & Sharing Model
61 questions
Q64. Is there any special permission available to edit read-only fields? Please explain.
Yes. At profile level of system administrator able to edit checkbox.
Q65. Mention one impact point to check before deleting a role from the org.
Check the impact on sharing settings and record access: role-based sharing rules, the role hierarchy above and below the role, users assigned to that role and any records shared through the role or its subordinates will lose or change access. You must reassign the users first, and sharing recalculation will run after the change.
Q66. What are the possible statuses of a permission set group?
Updated - the group is current.
Outdated - the group requires recalculation.
Updating - the group is in recalculation mode.
Failed - the group recalculation failed.
Q67. Once a lead is converted it is no longer visible in the UI. Is there a permission available to view converted leads?
Yes. There is an app permission called View and Edit Converted Leads, which allows users to view and edit converted lead records.
Q68. What happens when you try to delete a public group?
If the public group has been used in any sharing rule or is associated with any records in the context of sharing, Salesforce shows the associated references and records. You are then given the option to delete the public group along with the sharing of all those records. Removing the group triggers sharing recalculation, and users who gained access only through that group lose it.
Q69. What happens when you try to delete a queue?
If the queue is associated with any records or sharing rules, those references are displayed. The queue cannot be deleted until the references are removed - records owned by the queue must be reassigned and assignment rules or sharing rules referencing the queue must be updated.
Q70. What are the types of sharing rules in Salesforce?
There are 2 types of sharing rules, based on how the records to be shared are selected:
Owner-based sharing rules - share records owned by certain users, roles, roles and subordinates, or public groups.
Criteria-based sharing rules - share records whose field values meet defined criteria, regardless of owner.
Q71. How do we do manual sharing?
The Manual Sharing button (Sharing button on the record detail page in Classic, or Sharing in the Lightning record page's actions) allows a record owner - or a user with Full Access, or an administrator - to share an individual record with another user, group, role or territory with one click, choosing the access level (Read Only or Read/Write). It is used when an individual user wants to share their record with another colleague and no rule covers that case. Manual sharing is only available when the object's OWD is more restrictive than Public Read/Write.
Q72. What is Apex sharing?
When business requirements are too complex for the standard declarative sharing rules, you can grant access programmatically using Apex managed sharing. To share programmatically you use the share object associated with the standard or custom object - AccountShare for Account, and MyCustomObject__Share for a custom object.
public static boolean apexSharingDemo(Id recordId, Id userOrGroupId){
MyCustomObject__Share myCustomObject = new MyCustomObject__Share();
myCustomObject.ParentId = recordId;
myCustomObject.UserOrGroupId = userOrGroupId;
myCustomObject.AccessLevel = 'Read';
myCustomObject.RowCause = Schema.MyCustomObject__Share.RowCause.Manual;
Database.SaveResult[] jobShareInsertResult =
Database.insert(myCustomObject, false);
}
Apex managed sharing with a custom RowCause (an Apex sharing reason) survives owner changes and can only be maintained by users with Modify All Data.
Q73. What is the use of SECURITY_ENFORCED in a SOQL query?
When WITH SECURITY_ENFORCED is used in a SOQL query, Salesforce performs additional security checks to ensure that the running user has the necessary object-level and field-level permissions for all the objects and fields referenced in the SELECT and FROM clauses. If the user lacks access, the query throws a System.QueryException rather than silently returning data. (WITH USER_MODE and Security.stripInaccessible() are the newer alternatives.)
Q74. What is a profile?
A profile is a collection of permissions and settings that determines a user's functional access - which apps, tabs and objects they can use, object-level and field-level permissions, record types, page layouts, Apex class and Visualforce page access, and how information is displayed to the user. Every user must have exactly one profile.
Q75. What is the difference between a standard profile and a custom profile?
Standard profiles are included with Salesforce and are not fully customizable - certain permissions on them cannot be changed and they cannot be deleted. Custom profiles are created by the administrator (usually by cloning a standard profile) and are fully customizable, and can be edited, renamed and deleted.
Q76. What is a role in Salesforce?
Roles are defined to control and increase the data visibility a particular user has. Roles sit in a hierarchy, and users higher in the hierarchy can see the records owned by users below them. Record-level sharing can be done by:
Organization-Wide Defaults (OWD)
Role Hierarchy
Sharing Rules
Manual sharing, teams and Apex sharing
Q77. What is the difference between a profile and a role?
Also noted:
Roles are one of the ways you control access to records (data visibility, through the role hierarchy and sharing), while profiles determine what the user can do, view or edit - which objects and fields they can access, and which apps, tabs and system permissions they have. A user must have a profile; a role is optional.
Q78. How many standard profiles are available in Salesforce.com?
There are six standard user profiles in Salesforce. The most commonly used are:
System Administrator
Standard User
Read Only
Solution Manager
Marketing User
Contract Manager
(Note: there is no fixed number of six. The classic six above are the commonly-cited Sales/Service Cloud profiles, but which standard profiles exist depends on your edition and provisioned licences - modern orgs also ship Minimum Access - Salesforce (now the recommended baseline), Standard Platform User, Chatter Free, Chatter External User and the Experience Cloud portal profiles.)
Q79. What are organization-wide defaults (OWD), and what does each setting mean?
OWD sets the baseline level of access that the most restricted user should have to records they do not own:
Public Read/Write - records of the object are publicly available for reading and editing by all users of the organization.
Public Read Only - records are publicly available for reading only. Editing can be done only by the owner, an admin, and users above the owner in the role hierarchy.
Private - records are not available to other users. Only the owner, an admin and users above the owner in the role hierarchy can view and edit them.
Controlled by Parent (applied on a child object) - the access level given on the parent is applied to the child as well.
Public Read/Write/Transfer - records can be viewed, edited and transferred by users. This level is only available for the Lead and Case objects.
Also Public Full Access (Campaigns) and Private/Public Read Only external access levels for community users.
Q80. What is the role hierarchy?
The role hierarchy is a way to share records/data with users above in the hierarchy - a manager automatically gets at least the same access to records owned by (or shared with) users below them. It is configured at Setup > Role Hierarchy, and works only when the OWD is more restrictive than Public Read/Write and Grant Access Using Hierarchies is enabled.
Q81. What is field-level security?
Field-Level Security gives permissions at the field level to restrict a user's ability to view and edit particular fields on an object. It is controlled by Profiles and Permission Sets, and it applies everywhere - page layouts, list views, reports, search results and the API.
Q82. What is a permission set?
A permission set is a collection of settings and permissions that we want to assign to users - permission sets give extra rights or permissions to a user or a set of users on top of their profile.
Permission sets are used to grant extra rights or permissions, but cannot be used to restrict access to objects and fields.
A licence-based permission set can be assigned only to users of that specific licence.
A permission set with no associated licence can be assigned to any set of users.
Permission sets can be grouped into permission set groups with optional muting.
Also noted:
Navigate to Setup.
Enter "Permission Sets" in the Quick Find box and select Permission Sets.
Click New Permission Set and define its details, including the license and description.
Save the permission set, then add the required permissions and assign it to users.
Example: A user has only read access through their profile on a custom object, and the administrator wants to give them Edit and Create access without changing the profile. The administrator creates a permission set having Edit and Create operations on the custom object and assigns it to that user.
Q83. What is a public group?
Public Groups are to Roles what Permission Sets are to Profiles. An administrator can create ad hoc groups of users - naming them individually, or by roles, roles and subordinates, or other public groups - so that records can be shared with them.
A common use case is sharing records with users of a similar level, say Directors: as directors are spread throughout the organisation and are not under each other in the role hierarchy, an admin creates a public group containing all of the Director roles and shares records to that group.
Also noted:
Public groups consist of a set of users.
They are created to group users who have different profiles.
They can be used in sharing rules to share records.
They can be used in Salesforce Knowledge.
They can be used on report and dashboard folders to give access to the reports and dashboards inside them.
Q84. What are guest users in Salesforce?
Guest users are people without user accounts in your org. They are also called unauthenticated users because they don't need to log in. You can make pages - and data - publicly available to them, and they can even create or edit records. There are many considerations and limitations to evaluate, but the feature can solve a lot of use cases economically, as guest user licences are free. Since the Guest User Security policies were enforced, guest users are limited to Read access via a dedicated guest user profile and sharing rules, and cannot be given more than Read on most objects by OWD.
Q85. How do you ensure that a Flow adheres to the organization's security and sharing settings?
When designing a Flow, you can choose whether it should run in System Context or in the context of the current user. Running a Flow in System Context bypasses object-level and field-level security. To adhere to the organization's security and sharing settings, the Flow should run in the current user's context.
Q86. How do you give a user permission to access an Aura component?
Asked at: Mahindra & Mahindra
Component visibility and the data it shows are controlled through the standard security model, not through the component itself:
Setup > Users > Profiles (or a Permission Set) - grant the object and field permissions the component's controller needs, under Object Settings / Object Permissions.
Grant access to the Apex class that backs the component (Profile/Permission Set > Apex Class Access), otherwise the server-side action fails.
Control record-level access with OWD, role hierarchy, sharing rules, or programmatically by inserting ObjectName__Share records from Apex (Apex managed sharing).
On the Lightning page, use component visibility filters in the Lightning App Builder to show or hide the component per user, profile or record field value.
Q87. How do you handle the authentication part in Salesforce?
Asked at: GenPact
Set up an Auth. Provider: Setup > Auth. Providers > New > Salesforce (or another provider).
Salesforce provides multiple ways of authentication:
Username and password authentication.
Single Sign-On: the user logs in once to access multiple connected systems, using OAuth or SAML (Security Assertion Markup Language).
Social Sign-On: logins via Facebook, Google, etc.
Multi-Factor Authentication (MFA): time-based one-time passcodes (TOTP) and SMS.
Also noted:
The Auth. Provider issues a callback URL that is registered with the external system, and works with a Connected App using OAuth 2.0/SAML.
For outbound callouts, store the endpoint and credentials in a Named Credential so Apex does not handle tokens itself.
Q88. Where do you store credentials in Salesforce?
Asked at: Accenture
In Named Credentials.
Q89. How do you give permissions to a particular user via a permission set?
Asked at: Cloud 360
Answer supplied - source left blank.
Permission sets grant extra access on top of the profile, without changing the profile.
1. Setup > Permission Sets > New - give it a label and (optionally) a licence.
2. Add the permissions: Object Settings (object CRUD and field-level security), Apex Class Access, Visualforce Page Access, System Permissions, tab settings, record types, and custom permissions.
3. Assign it: from the permission set click Manage Assignments > Add Assignments and pick the user, or from Setup > Users > (user) > Permission Set Assignments > Edit Assignments.
4. Use a Permission Set Group with muting when many sets must be bundled for a persona.
Remember: permission sets can only grant access, never restrict it.
Q90. What are the levels at which we can restrict a user's access to records?
Asked at: Cloud 360
Answer supplied - source left blank.
Salesforce security is layered, and records can be restricted at each level:
Organisation level - trusted IP ranges, login hours, password policies.
Object level - profiles and permission sets (Create, Read, Edit, Delete, View All, Modify All).
Field level - field-level security on profiles and permission sets.
Record level - Organisation-Wide Defaults (OWD), role hierarchy, sharing rules (owner-based and criteria-based), manual sharing, teams (account/opportunity/case), territory management and Apex managed sharing.
OWD sets the most restrictive baseline; every other mechanism only opens access up.
Q91. What default access levels are available in the organization-wide defaults (OWD)?
Asked at: Cloud 360
The internal access options are:
Private
Public Read Only
Public Read/Write
Public Read/Write/Transfer (Lead and Case only)
Plus Controlled by Parent for child objects in a master-detail relationship, and Public Full Access for Campaigns.
Q92. In OWD there are three columns - internal user, external user and guest user. If the internal user access is set to Private, can the external user have Read/Write access?
Asked at: Cloud 360
No. The external access level can never be more permissive than the internal access level. If internal access is Private, external (and guest) access must also be Private or more restrictive, so Read/Write cannot be granted to external users.
Q93. Scenario: how do you give a specific user permission on a particular object?
Asked at: Cloud 360
Use a permission set assigned to that single user, which grants the object and field permissions on top of their profile - this avoids creating a new profile just for one person. Record-level access is then handled with sharing settings (OWD, sharing rules, manual sharing).
Q94. What happens if one profile has Read/Write access and another has Write/Delete access on the same object?
Asked at: Cloud 360
Answer supplied - source left blank.
A user has only one profile, so the situation arises when a profile is combined with permission sets (or when comparing two users).
Object permissions are cumulative and additive: the user ends up with the union of the permissions granted by their profile and all assigned permission sets.
So a profile granting Read/Edit plus a permission set granting Edit/Delete results in Read, Edit and Delete.
Permission sets can only add rights; they can never remove what the profile grants (only a Permission Set Group with muting can mute a permission).
Delete also requires Read; the more permissive setting always wins.
Q95. How do you make a set of data visible to Role A also visible to Role B?
Answer supplied - source left blank.
Roles only share upward through the hierarchy, so a peer role does not see another peer's records by default. To open access sideways:
Sharing Rules (owner-based or criteria-based) - create a sharing rule that shares records owned by Role A (or matching criteria) with the Role B public group/role, with Read Only or Read/Write access.
Public Groups - if several roles need the same access, put them into a public group and share to that group.
Manual Sharing - for one-off record access by the owner.
Apex Managed Sharing - for complex, programmatic rules that the declarative tools cannot express.
Note that this only widens access above the Organization-Wide Default; if the OWD is Public Read/Write, sharing rules are unnecessary.
Q96. In how many ways can we share a record in Salesforce?
Role Hierarchy: If we add a user to a role, the user above in the role hierarchy will have read access.
Setup -> Manage Users -> Roles -> Setup Roles -> click on 'Add Role' -> provide name and save.
OWD (Organization-Wide Defaults): Defines the baseline setting for the organization. Defines the level of access a user can have to another user's record. OWD can be Private, Public Read Only, or Public Read/Write.
Setup -> Security Controls -> Sharing Settings -> click on 'Edit'.
Manual Sharing: Manual sharing is sharing a single record with a single user or group of users. We can see this button on the detail page of the record and it is visible only when the OWD setting is Private.
Criteria-Based Sharing Rules: If we want to share records based on a condition, e.g. share records with a group of users whose criteria is Country = India.
Setup -> Security Controls -> Sharing Settings -> select the object, provide name and conditions and save.
Apex Sharing: A share object is available for every object (for the Account object the share object is AccountShare). If we want to share records using Apex we have to create a record in the share object.
Also noted:
Profile / permission set object-level CRED access
View All and Modify All permissions on the profile or permission set
Profile-level system permissions
Organization-Wide Defaults (OWD)
Record ownership
Role hierarchy
Case Team, Account Team and Opportunity Team
Queues
Sharing rules (owner-based and criteria-based)
Public groups
Territory management
Sharing sets (for Experience Cloud users)
Share groups
Super User access (partner/customer community)
Manual sharing
Apex managed sharing
Visualforce pages with Apex (without sharing)
Implicit sharing (built-in account-contact/case/opportunity sharing)
Master-detail relationship (child inherits parent access)
External account hierarchy
Q97. Can I find out if the current user has access to a record without querying?
To find out if a particular user has Edit access to a record, use the UserRecordAccess object. This object is available in API version 24.0 and later. You can use SOQL to query this object to find out if the user has edit access to the record in question:
SELECT RecordId, HasEditAccess FROM UserRecordAccess
WHERE UserId = [single ID] AND RecordId = [single ID]
If you want to check a batch of records you can use:
SELECT RecordId FROM UserRecordAccess
WHERE UserId = :UserInfo.getUserId()
AND HasReadAccess = true AND RecordId IN :allRecordIds LIMIT 200
But make sure that allRecordIds is a LIST of IDs - it doesn't work if allRecordIds is a SET of IDs. Also, only a maximum of 200 record IDs can be checked in one query.
Q98. Explain the use of 'Transfer Record' in a profile.
If a user has only Read access on a particular record but wants to change the owner name of that record, then if Transfer Record is enabled at the profile level, he will be able to change the owner.
Q99. What are sharing rules, and when do they apply?
A sharing rule is a way of sharing records automatically with the users of a specific role, group or territory.
Records can be shared owner based (based on roles and public groups) or criteria based (records that match a filter criterion).
Sharing rules work only if the OWD of the object is set to Private or Public Read Only - they can only open up access, never restrict it.
Sharing is automatic and applies to existing records as well as new ones.
Governor limits: 300 sharing rules per object in total (250 owner/role based + 50 criteria based).
Setup > Quick Find > Sharing Settings.
Manual sharing is the complementary manual option: records are shared one by one with a particular user or group by clicking the Sharing button on the record page. It also works only when OWD is Private or Public Read Only.
Also noted:
They can be based on record ownership (owner-based) or on other criteria (criteria-based field values).
You select which records to share, which users or groups to share them with, and the level of access (Read Only or Read/Write) to be given.
For example, an account sharing rule can be created based on the account owner or on other criteria such as account type.
Q100. Can you change or bypass the 'Grant Access Using Hierarchies' setting for standard objects?
No. For standard objects this setting is enabled by default and cannot be changed. It can only be unchecked for custom objects.
Q101. Can two users have the same profile?
Yes. A single profile can be assigned to many users.
Q102. What does 'with sharing' mean in an Apex class?
When you use with sharing, the sharing rules of the current user are enforced. With without sharing, the code runs in system mode and sharing rules are not enforced.
(Note: The with sharing keyword enforces record-level sharing rules. Field-level security and object permissions are not enforced by with sharing alone; use WITH SECURITY_ENFORCED, Security.stripInaccessible() or userMode for those.)
Q103. Can a user change his or her own profile in Salesforce?
No, a user cannot change their own profile.
Q104. Can a user change his or her own role?
Yes, this can be done (a user with the appropriate administrative permission can change their own role).
Q105. The "Reset Security Token" option is unavailable in Setup. What could be the reason?
If "Login IP Ranges" have been set up in the user's profile settings, the "Reset Security Token" option is not available, because a token is not needed for logins from within the trusted IP range.
Q106. Can you create a new profile from scratch?
No. You have to clone an existing profile and modify its settings as required.
Q107. Can you use sharing rules to restrict data access?
No. Sharing rules can only grant wider access to data; they cannot restrict access below what the org-wide defaults allow.
Q108. Can you create sharing rules for detail objects?
No. Detail objects cannot have sharing rules, because a detail object does not have an Owner field; its access is controlled by its parent.
Q109. What is the use of writing sharing rules?
Sharing rules extend the record/data access level that is set using the org-wide defaults and the role hierarchy. A sharing rule cannot restrict data visibility; it can only widen it.
Q110. Can you set the default access in the organization-wide defaults for detail objects (in a master-detail relationship)?
No. A detail object always has an access level of 'Controlled by Parent' and it cannot be changed.
Q111. Can a user not have a role?
Yes, this is possible. A role is not mandatory for a user.
Q112. Can a user not have a profile?
No, a user must always have a profile. Unlike a role, a profile is mandatory.
Q113. When writing a sharing rule, with whom can you share the records?
Records can be shared with Roles, Roles and Subordinates, and Public Groups.
Q114. Can you use a single permission set for multiple users?
Yes. Once created, a permission set can be added to multiple users, either from the related list on the user detail page or to many users at once from Setup.
Q115. If you have a custom object acting as the detail in a master-detail relationship with a standard object, what will its organization-wide default be set to?
The OWD for a detail object is always 'Controlled by Parent' and this cannot be edited.
Q116. View or Edit permission on a document, report, or dashboard depends on whether the user has access to the folder in which it is stored - true or false?
True. Access to documents, reports and dashboards is governed by access to the folder in which they are stored.
Q117. What are the different types of groups that you can create in Salesforce?
Two types of groups can be created:
Public group
Personal group
Q118. What is the use of permission sets?
Permission sets are used to extend a user's functional access without changing their assigned profile, so several users on the same profile can be granted extra permissions individually.
Q119. What are the different levels of data security in Salesforce?
Data security means securing the organization and its data at four levels.
1. Organization level security
Login IP ranges (Setup > Network Access, or at profile level).
Login hours (set at profile level).
Password policies (Setup > Password Policies).
Users cannot be deleted in an org; they can only be frozen or deactivated. A frozen user cannot log in but still holds a license and still owns/keeps access to records; a deactivated user cannot log in, the license is released and the records are no longer available to that user.
2. Object level security - controls create, read, edit and delete on an object.
Profiles - the minimum level of access given to a user.
Permission sets - extra rights on top of the profile.
3. Field level security - securing individual fields of an object.
Profiles.
Permission sets.
4. Record level security - securing the records of one user from another user.
OWD (Organization-Wide Defaults).
Role hierarchy.
Sharing rules.
Manual sharing.
Q120. What is the difference between a Profile and a Permission Set?
Profile
A profile is the minimum/basic level of access and rights given to a user. It defines which objects and fields are accessible to a user associated with that profile.
Every user must have at least and at most one profile, but one profile can be assigned to many users.
Profiles depend on the license type.
Profiles can be standard (predefined, cannot be edited or deleted, but can be cloned) or custom (created by cloning a standard profile, can be edited or deleted).
A profile can both grant and restrict access.
Permission Set
A permission set is a combination of permissions used to give extra rights to a user or a set of users on top of what the profile allows.
Permission sets cannot be used to restrict access to objects and fields - they only add access.
Permission sets are optional and a user can be assigned many of them.
A license-based permission set can be assigned only to users of that specific license; a "none" (no license) based permission set can be assigned to any set of users.
Q121. What are the four record-level security mechanisms in Salesforce, and how do they interact?
1. Organization-Wide Defaults (OWD) - the baseline level of access to each object; the most restrictive setting.
2. Role hierarchy - opens access upwards: users higher in the hierarchy inherit access to records owned by users below them. Users who need access to the same types of records are grouped together in a role.
3. Sharing rules - open access to a group, role or role-and-subordinates based on record ownership or on criteria.
4. Manual sharing - the record owner (or someone above them in the hierarchy) grants access to an individual record.
Key principle: OWD sets the floor. Whatever restrictions you set in OWD are opened up - never tightened - by role hierarchy, sharing rules and manual sharing. You cannot use those mechanisms to restrict access below the OWD level.
Q122. How does Apex managed sharing work, and how do you share a record programmatically?
There are three types of sharing: managed sharing (done by Salesforce - ownership, role hierarchy, sharing rules), user managed sharing (manual sharing by the owner) and Apex managed sharing (created in code with a custom row cause).
Every object that can be shared has a corresponding share object. For standard objects it is named like AccountShare or OpportunityShare; for custom objects it is MyObject__Share. You cannot create a __Share object yourself - the system creates it for you. If the object's sharing setting is Public Read/Write, no share object is created because there is nothing to share; if the setting is Public Read Only or Private, the system creates the share object.
Set<Id> oppIds = new Set<Id>();
Id newOwnerId;
List<OpportunityShare> oppShares = new List<OpportunityShare>();
for (Id i : oppIds) {
OpportunityShare os = new OpportunityShare();
os.OpportunityId = i;
os.OpportunityAccessLevel = 'Read/Write';
os.UserOrGroupId = newOwnerId;
// os.RowCause = 'Manual Sharing';
oppShares.add(os);
}
Database.SaveResult[] result = Database.insert(oppShares, false);
For a custom object the fields are named ParentId, AccessLevel, UserOrGroupId and RowCause. Use a custom Apex sharing reason as the RowCause so that the sharing survives owner changes and can be identified later.
Q123. What is the difference between with sharing, without sharing and inherited sharing in Apex?
with sharing - the class respects the sharing model of the running user, so record-level access (OWD, role hierarchy, sharing rules) is enforced in queries and DML.
without sharing - the class ignores the sharing rules, so it runs in system mode and sees all records. Use it deliberately, for example in a service that must roll up data the user cannot see.
inherited sharing - the class uses the sharing mode of the calling class. If it is entered directly (as a REST endpoint, a Visualforce controller, and so on) it defaults to with sharing. This is the safest declaration for reusable service classes.
Note that sharing keywords control record-level access only. Object-level and field-level security are not enforced automatically in Apex - use WITH SECURITY_ENFORCED in SOQL or Security.stripInaccessible() for that.
Q124. How do you enforce object-level and field-level security in Apex code?
Add WITH SECURITY_ENFORCED to a SOQL query to enable field-level and object-level permission checking for the fields in the SELECT and FROM clauses. The query throws an exception if the running user lacks access.
List<Contact> cons = [SELECT Id, Name, Email FROM Contact WITH SECURITY_ENFORCED];
Use Security.stripInaccessible() to sanitize results and prepare records for DML instead of throwing:
// Strip fields from SOQL results that fail FLS checks
SObjectAccessDecision decision = Security.stripInaccessible(AccessType.READABLE, myContacts);
List<Contact> readable = (List<Contact>) decision.getRecords();
// Prepare for DML operations
SObjectAccessDecision securityDecision = Security.stripInaccessible(AccessType.CREATABLE, newContacts);
insert securityDecision.getRecords();
You can also check describe results explicitly (Schema.sObjectType.Contact.fields.Email.isAccessible()), and add a validation message to a record with object.addError('message');.
Asynchronous Apex
106 questions
Q125. Can we call a batch from another batch Apex?
Yes, we can call another batch job from the finish method of a batch class.
Q126. Can we call a batch Apex class from another batch's execute method?
No. We can only call another batch class from the batch class's finish method. If you call another batch class from the batch class's execute or start method, Salesforce throws the following runtime error:
System.AsyncException: Database.executeBatch cannot be called from a batch start, batch execute, or future method.
Q127. Can we call batch Apex from triggers in Salesforce?
Yes, it is possible. We can call a batch Apex class from a trigger, but we should always keep in mind that we should not call batch Apex from a trigger every time, as this will exceed the governor limit. This is because we can only have 5 Apex jobs queued or executing at a time.
Q128. Explain Batch Apex with a web service callout.
global class AccountBatchApex implements Database.Batchable<sObject>, Database.AllowsCallouts {
global Database.QueryLocator start(Database.BatchableContext bc){
String soqlQuery = 'SELECT Name, AccountNumber, Type From Account';
return Database.getQueryLocator(soqlQuery);
}
global void execute(Database.BatchableContext bc, List<Account> scope){
for (Account acc : scope){
if(acc.Type.equals('Customer - Direct')){
try{
HttpRequest request = new HttpRequest();
HttpResponse response = new HttpResponse();
Http http = new Http();
String username = 'YourUsername';
String password = 'YourPassword';
Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
request.setHeader('Authorization', authorizationHeader);
request.setHeader('Content-Type', 'application/json');
request.setEndpoint('Your Endpoint URL');
request.setMethod('POST');
request.setBody('Information to Send');
response = http.send(request);
if (response.getStatusCode() == 200) {
String jsonResponse = response.getBody();
System.debug('Response-' + jsonResponse);
}
}
catch(Exception e){
System.debug('Error-' + e.getMessage());
}
}
}
}
global void finish(Database.BatchableContext bc){
}
}
Q129. How many times will the start, execute and finish methods execute in Batch Apex?
The start method and the finish method execute one time each. The execute method runs once per batch - the number of times depends on the requirement, specifically on the batch size and the number of records retrieved in the start method (records retrieved divided by the batch size, rounded up).
Q130. What is the batch execution limit per day?
The maximum number of batch executions is 250,000 per 24 hours (or the number of user licences in the org multiplied by 200, whichever is greater). Up to 5 batch jobs can be queued or active concurrently, and up to 100 holding batch jobs can be held in the flex queue.
Q131. Can we call a future method from Batch Apex?
Asked at: GenPact
No. Future methods are not allowed in a batch class (nor from another future method). If you need asynchronous follow-up work from a batch, use Queueable Apex (System.enqueueJob) from the finish() method instead.
Also noted:
Methods declared as @future aren't allowed in classes that implement the Database.Batchable interface.
Methods declared as @future can't be called from a batch Apex class.
No, we can't. A future method cannot be invoked from Batch Apex - attempting it throws an async exception. Use a queueable job or a callout from within the batch (with Database.AllowsCallouts) instead.
Q132. Does a future method support primitive data types? Why are sObject parameters not supported?
The reason sObjects can't be passed as arguments to future methods is that the sObject might change between the time you call the method and the time it executes. In that case the future method will get the old sObject values and might overwrite them.
Q133. How can I perform callouts from future methods?
Add the callout=true parameter to the annotation: @future(callout=true). Without it, any callout attempted from the future method throws a CalloutException.
Q134. Can I write a future call in a trigger?
Yes, you can invoke a future method from a trigger. Keep in mind the limits:
The maximum number of future method invocations per 24-hour period is 250,000, or the number of user licences in your organization multiplied by 200, whichever is greater.
A future method can't invoke another future method.
No more than 50 future method calls are allowed per Apex invocation.
Because triggers run in bulk, the future call should be made once with a collection of Ids rather than once per record.
Q135. What is a future method (the @future annotation) in Salesforce?
Future methods are used to isolate DML operations on different sObject types to prevent the mixed DML error. Each future method is queued and executes when system resources become available. That way, the execution of your code doesn't have to wait for the completion of a long-running operation. A benefit of using future methods is that some governor limits are higher, such as SOQL query limits and heap size limits.
Notes:
Methods with the future annotation must be static methods.
They can only return a void type.
The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types.
Methods with the future annotation cannot take sObjects or objects as arguments.
You can invoke future methods the same way you invoke any other method. However, a future method can't invoke another future method.
No more than 50 method calls per Apex invocation.
Asynchronous calls, such as @future or executeBatch, called in a startTest/stopTest block, do not count against your limits for the number of queued jobs.
The maximum number of future method invocations per 24-hour period is 250,000, or the number of user licenses in your organization multiplied by 200, whichever is greater.
To test methods defined with the future annotation, call the class containing the method in a startTest()/stopTest() code block. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously.
Also noted:
Callouts to external web services. If you are making callouts from a trigger, you must use a future or Queueable method.
Operations you want to run in their own thread, when time permits, such as some sort of resource-intensive calculation or processing of records.
Preventing the mixed DML error.
Q136. How can I use the job Id to trace an asynchronous job?
Perform a SOQL query on AsyncApexJob, filtering on the job Id returned by System.enqueueJob or Database.executeBatch:
AsyncApexJob jobInfo = [SELECT Status, NumberOfErrors
FROM AsyncApexJob WHERE Id = :jobID];
Other useful fields are JobItemsProcessed, TotalJobItems, ExtendedStatus, CreatedDate and CompletedDate.
Q137. Can I do callouts from a Queueable job?
Yes. You have to implement the Database.AllowsCallouts interface to make callouts from a queueable job:
public class MyQueueable implements Queueable, Database.AllowsCallouts { ... }
Q138. How many jobs can I queue using System.enqueueJob() at a time?
You can add up to 50 jobs to the queue with System.enqueueJob in a single transaction in synchronous Apex. In asynchronous transactions, you can add only one job to the queue.
Q139. Can I call a Queueable job from a batch?
Yes, but you're limited to just one System.enqueueJob call per execute in the Database.Batchable class. Salesforce has imposed this limitation to prevent explosive execution.
Q140. If I have written more than one System.enqueueJob call, what will happen?
The system will throw a LimitException stating "Too many queueable jobs added to the queue: N".
Q141. I have a use case to call more than one Queueable job from a Batch Apex. How can I achieve it?
Since we can't call more than one queueable job from each execution context, we can schedule the queueable jobs instead. The approach is:
1. Check how many queueable jobs have already been added to the queue in the current transaction, using the Limits class (Limits.getQueueableJobs() against Limits.getLimitQueueableJobs()).
2. If the number has reached the limit, call a schedulable class instead.
3. Enqueue the remaining queueable classes from the execute method of that schedulable class.
Q142. What considerations must be followed when using the @future annotation on an Apex method?
Future methods must be static methods.
They can only return a void type.
The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types.
Notably, future methods can't take standard or custom objects as arguments. You can pass the list of record IDs that you want to process asynchronously.
Q143. Can we fix the order in which future methods will run?
Future methods are not guaranteed to execute in the same order as they are called. When using future methods, it's also possible that two future methods could run concurrently, which could result in record locking.
Q144. How do you call future methods from Process Builder?
To call future methods from Process Builder, call the future method from an invocable method.
Q145. What is the best approach for making callouts to external web services?
A future method invoked through a trigger is allowed to do Apex callouts and invoke an external web service, provided the future method is annotated with @future(callout=true). This provides a lot of flexibility and is one of the best approaches.
Q146. What are the best practices for future methods?
Every future method invocation adds one request to the asynchronous queue, so avoid design patterns that add large numbers of future requests over a short period of time.
Ensure that future methods execute as fast as possible.
If using web service callouts, try to bundle all the callouts together in the same future method rather than using a separate future method for each callout.
Consider using Batch Apex instead of future methods to process a large number of records asynchronously.
Future methods must be static, return void, and accept only primitive data types, arrays of primitives or collections of primitives as parameters.
Test at scale. Make sure a trigger that enqueues @future calls can handle a full collection of 200 records, so you find out whether delays or limit breaches appear at current and future data volumes before production does.
Q147. Can we use future methods in Visualforce controllers or constructors?
Future methods can't be used in Visualforce controllers in getMethodName(), in setMethodName(), nor in the constructor.
Q148. Can we call one future method from another future method?
Asked at: GenPact
No. A future method cannot call another future method. If chaining is required, use Queueable Apex, which supports chaining with System.enqueueJob().
Q149. What are the limits of future methods?
Asked at: Accenture
50 - the governor limit is 50 future method calls per Apex invocation/transaction (within a class). Also remember: future methods must be static void with primitive parameters, cannot be called from a batch or from another future method, and there is a 24-hour org limit of 250,000 asynchronous executions or 200 x the number of licences, whichever is greater.
Also noted:
It is not a good option to process large numbers of records.
Only primitive data types are supported.
Tracing a future job is also difficult.
You can't call a future method from batch and future contexts; 1 call from a Queueable context is allowed.
Q150. How do you monitor future methods?
Future jobs show up on the Apex Jobs page like any other job.
You can query AsyncApexJob to find your future job. Since a running future job does not return an ID, you have to filter on some other field such as MethodName or JobType to find your job.
Q151. What are the use cases of future methods?
Make a callout to an external web service.
Avoid the MIXED_DML_OPERATION exception.
Q152. Is it possible to call a future method from an Apex scheduler or not?
Yes, it is possible to call a future method from an Apex scheduler.
// Scheduled Apex
public class DemoScheduler1 implements Schedulable {
public void execute(SchedulableContext sc) {
system.debug('*******Going to call future method ');
DemoAsynchronousTest.futureMethodCallFromScheduler();
}
}
// Apex class containing the future method
public class DemoAsynchronousTest {
@future
public static void futureMethodCallFromScheduler() {
system.debug('******futureMethodCallFromScheduler get called');
}
}
Q153. Why is a future method static and void?
Future methods will run in the future. You don't want your synchronous code waiting an unknown period of time for an asynchronous bit of code to finish working. By only returning void, you can't have code that waits for a result.
A future method is by definition static, so that variables within this method are associated with the class and not with the instance, and you can access them without instantiating the class.
Q154. What could be the workaround for sObject types in a future method?
To work with sObjects, pass the sObject ID instead (or a collection of IDs) and use the ID to perform a query for the most up-to-date record.
global class FutureMethodRecordProcessing {
@future
public static void processRecords(List<ID> recordIds) {
// Get those records based on the IDs
// Process records
}
}
Q155. If I want to call a future method from a future method, what could be the solution?
The workaround could be calling a web service that has a future invocation.
Q156. From which places can we call a future method?
Trigger
Apex class
Schedulable class
Q157. From which places can we call a batch class?
Batch finish() method
Schedule
Apex class
Triggers
Q158. From which places can we call a schedule class?
Batch finish() method
Schedule
Q159. From which places can we call a Queueable class?
Batch finish() method
One System.enqueueJob() in asynchronous context
Schedule - for queue
Q160. Can we pass a wrapper to a future method?
You can pass a wrapper, but for that you'll need to serialize/deserialize that parameter. You can convert the wrapper to a String, which is a primitive.
Once converted into a String, you can then pass that string as a parameter to the future method in consideration.
Q161. Explain how to avoid the mixed DML error.
Perform the second DML operation (the setup object DML) inside a future method.
public class Util {
@future
public static void insertUserWithRole(
String uname, String al, String em, String lname) {
Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
UserRole r = [SELECT Id FROM UserRole WHERE Name='COO'];
// Create new user with a non-null user role ID
User u = new User(alias = al, email=em,
emailencodingkey='UTF-8', lastname=lname,
languagelocalekey='en_US',
localesidkey='en_US', profileid = p.Id, userroleid = r.Id,
timezonesidkey='America/Los_Angeles',
username=uname);
insert u;
}
}
public class MixedDMLFuture {
public static void useFutureMethod() {
// First DML operation
Account a = new Account(Name='Acme');
insert a;
// This next operation (insert a user with a role)
// can't be mixed with the previous insert unless
// it is within a future method.
// Call future method to insert a user with a role.
Util.insertUserWithRole(
'mruiz@awcomputing.com', 'mruiz',
'mruiz@awcomputing.com', 'Ruiz');
}
}
Q162. What is Asynchronous Apex in Salesforce, and what types of asynchronous processing are available?
Future methods: the basic asynchronous feature, used when we make a web callout or when we want to prevent the mixed DML error.
Batch Apex: to do bulk processing of records, or for jobs that require larger query results - for example, processes like database maintenance jobs.
Scheduled Apex: used to schedule the invocation of an Apex class at a specific time; this can be a recurring event or a one-time task.
Queueable Apex: used when one task is dependent on the completion of another task. Also, job chaining and complex types of jobs are achieved using this feature.
Also noted:
With synchronous Apex you can hit limit errors, heap size errors or timeout errors while processing bulk data. To avoid such issues, long-running or time-consuming operations can be performed with asynchronous Apex, which runs processes in the background at a later time when resources are available.
An asynchronous process is a process or function that executes a task "in the background" without the user having to wait for the task to finish. Asynchronous Apex is used to run processes in a separate thread.
Future methods - methods annotated with @future, used to run long-running operations such as callouts to external web services in their own thread.
Batch Apex - used to run large jobs that process millions of records.
Queueable Apex - like future methods, but with the ability to chain jobs and to accept complex types.
Scheduled Apex - classes scheduled to run at a specific time.
They run in the background; the calling process does not wait for one process to complete before starting another.
They get higher governor limits (many limits are doubled compared with a synchronous transaction).
They can all be started from a trigger.
Avoid child queries and try to use a single SOQL query.
You cannot call a future method from a Batch class, but you can enqueue a Queueable from one.
The flow of an async request is: Request => Enqueue (every request arrives here) => Persistence (the request is stored) => Dequeue (the request is processed with transaction management).
Q163. Why use Batch Apex in Salesforce instead of normal Apex?
A batch class allows you to define a single job that can be broken up into manageable chunks that will be processed separately.
One example is if you need to make a field update to every Account in your organization. If you have 10,001 Account records in your org, this is impossible without some way of breaking it up. So in the start() method you define the query you're going to use in this batch context: select Id from Account. Then the execute() method runs, but only receives a relatively short list of records (default 200). Within the execute(), everything runs in its own transactional context, which means almost all of the governor limits only apply to that block. Thus each time execute() is run, you get a fresh set of governor limits: 200 SOQL queries (asynchronous), 50,000 query rows, 150 DML statements and 10,000 DML rows and so on. When that execute() is complete, a new one is instantiated with the next group of 200 Accounts, with a brand new set of governor limits. Finally the finish() method wraps up any loose ends as necessary, like sending a status email.
So your batch that runs against 10,000 Accounts will actually be run in 50 separate execute() transactions, each of which only has to deal with 200 Accounts. Governor limits still apply, but only to each transaction, along with a separate set of limits for the batch as a whole.
Disadvantages of batch processing:
It runs asynchronously, which can make it hard to troubleshoot without some coded debugging, logging and persistent stateful reporting. It also means that it's queued to run, which may cause delays in starting.
There's a limit of 5 batches in play at any time, which makes it tricky to start batches from triggers unless you are checking limits.
If you need access within execute() to some large part of the full dataset being iterated, this is not available. Each execution only has access to whatever is passed to it, although you can persist class variables by implementing Database.Stateful.
There is still a (fairly large) limit on total heap size for the entire batch run, which means that some very complex logic may run over and need to be broken into separate batches.
Also noted:
Every batch transaction starts with a new set of governor limits.
The system itself divides the records into batches for you, based on the scope size.
If one batch fails, the other batches continue to be executed, and successful batches are still committed to the database - successful batches are not rolled back when one batch fails.
Batch Apex can query up to 50 million records via Database.QueryLocator, and can be scheduled and chained.
Q164. Which interface will you use for batch Apex?
It is the Database.Batchable interface.
Q165. What are the methods of a Batch Apex class?
A batch class implements the Database.Batchable interface with three methods:
start()- used at the beginning of the Batch Apex job. It collects the records or objects to pass to the interface method execute. It returns either aDatabase.QueryLocatorobject or anIterablethat contains the records or objects passed into the job.execute()- used for each batch of records that are passed to the method. This method performs all the processing of the data. It takes two arguments: a reference to theDatabase.BatchableContextobject, and a list of sObject records.finish()- called once all the batches are processed. It is used for sending confirmation emails or executing post-processing operations. It takes one argument, the reference to the Database.BatchableContext object.The default batch size is 200 records per execute() call. You can override it with the optional scope argument of Database.executeBatch(batchable, scope), up to a maximum of 2,000 (and 2,000 is also the ceiling when the start method returns a QueryLocator).
Batches are not guaranteed to execute in the order they are received from the start() method. If ordering matters, sort inside execute() or use Database.Stateful to accumulate and finish the work in finish().
Q166. What are the parameters passed in the execute method of batch Apex?
This method takes the following:
A reference to the Database.BatchableContext object.
A list of sObjects, such as List<sObject>, or a list of parameterized types. If you are using a Database.QueryLocator, use the returned list.
Q167. What is the use of Database.Stateful?
If you specify Database.Stateful in the class definition, you can maintain state across all transactions. When using Database.Stateful, only instance member variables retain their values between transactions. Maintaining state is useful for counting or summarizing records as they're processed. For example, if we're updating contact records in our batch job and want to keep track of the total records affected so we can include it in the notification email.
Also noted:
The implication is the cost of serializing and deserializing your state between every execute. Consider your batch size: if you're doing a million records and your batch size is 1, then you will serialize/deserialize your state 1 million times. Even with a small serialized object, that is going to hurt performance.
Q168. When should you use batch Apex instead of Queueable Apex?
You should use Batch Apex only if you have more than one batch of records. If you don't have enough records to run more than one batch, you should use Queueable Apex.
Q169. How can you monitor a batch Apex job?
A batch Apex job can be monitored by navigating to Your Name -> Setup -> Monitoring -> Apex Jobs.
Q170. How do you use HTTP callouts in a batch class?
To use HTTP callouts in a batch class we need to implement the Database.AllowsCallouts interface.
Q171. How do you schedule a batch?
Using scheduled Apex we can schedule a batch.
Q172. If a batch has 200 records and 1 record fails, what will happen?
If any record fails, all 200 records will fail, but the next batch will still get executed.
Q173. What is the Apex Flex queue?
The Apex Flex queue enables you to submit up to 100 batch jobs for execution. Any jobs that are submitted for execution are in Holding status and are placed in the Apex Flex queue. Up to 100 batch jobs can be in the Holding status.
Q174. Can you change the order of (prioritise) jobs pending in the Apex Flex queue?
Jobs are processed first-in, first-out - in the order in which they're submitted. You can look at the current queue order and shuffle the queue, so that you could move an important job to the front, or less important ones to the back.
Boolean isSuccess = System.FlexQueue.moveBeforeJob(jobToMoveId, jobInQueueId);
Also noted:
This can be done by reordering jobs from Setup -> Apex Flex Queue, or through Apex code using the FlexQueue methods, for example System.FlexQueue.moveAfterJob() and moveBeforeJob().
Q175. How many jobs can run concurrently?
The system can process up to five queued or active jobs simultaneously for each organization.
Q176. Explain the statuses of jobs in the Apex Flex queue.
Holding: Job has been submitted and is held in the Apex Flex queue until system resources become available to queue the job for processing.
Queued: Job is awaiting execution.
Preparing: The start method of the job has been invoked. This status can last a few minutes depending on the size of the batch of records.
Processing: Job is being processed.
Aborted: Job aborted by a user.
Completed: Job completed with or without failures.
Failed: Job experienced a system failure.
Q177. Can I use FOR UPDATE in a SOQL query with Database.QueryLocator?
No, we can't. It will throw an exception stating that "Locking is implied for each batch execution and therefore FOR UPDATE should not be specified".
Q178. Can I query related records using Database.QueryLocator?
Yes, you can do a subquery for related records, but with a relationship subquery the batch job processing becomes slower. A better strategy is to perform the subquery separately, from within the execute method, which allows the batch job to run faster.
Q179. How can you stop a batch job?
The Database.executeBatch and System.scheduleBatch methods return an ID that can be used in the System.abortJob method.
Q180. Give an example of Iterable.
global class MyTest implements Iterable<Account>
{
}
global Iterable<Account> start(Database.BatchableContext bc)
{
// This should return an object of the class that has implemented the Iterable interface.
return new MyIterableClass();
}
Q181. Write a batch Apex program to update the phone number on the Contact object with the phone number from the corresponding Account object, where Contact is a child of Account.
global class ContactUpdate implements Database.Batchable<sObject>
{
global Database.QueryLocator start(Database.BatchableContaxt bc)
{
String query = 'select id, phone, Account.phone from Contact';
return Database.getQueryLoactor(query);
}
global void execute(Database.BatchableContext bc, List<Contact> scope)
{
for(contact con: scope)
{
con.phone = con.Account.phone;
Conlist.add(con);
}
update con;
}
global void finish(Database.Batchable Context bc)
{
}
}
Q182. Create an Apex class to invoke a batch Apex job.
public class TestMyBatch
{
public string cname{get; set;}
public pageReference show()
{
customerBatch mybatch = new customerBatch (cname);
Id id = Database.executeBatch (mybatch, 400);
system.debug ('My Job id' + id);
return null;
}
}
(Note: show() is declared to return a PageReference, so it must end with a return statement or the class will not compile - return null; keeps the user on the same page. 400 is the batch scope size; the default is 200 and the maximum is 2,000.)
Q183. How do you use aggregate queries in Batch Apex?
Aggregate queries don't work in Batch Apex because aggregate queries don't support queryMore(). They run into the error: 'Aggregate query does not support queryMore(), use LIMIT to restrict the results to a single batch'.
To fix this error:
1. Create an Apex class that implements Iterator<AggregateResult>.
2. Create an Apex class that implements Iterable<AggregateResult>.
3. Implement Database.Batchable<AggregateResult>, and use the Iterable at start execution in the Batch Apex.
Q184. What is the difference between Database.Batchable and Database.BatchableContext?
1. Database.Batchable is an interface.
2. Database.BatchableContext is a context variable that stores runtime information, e.g. the job ID.
Q185. Which platform event can be fired from a batch?
The BatchApexErrorEvent object represents a platform event associated with a batch Apex class.
It is possible to fire platform events from batch Apex. So whenever any error or exception occurs, you can fire platform events which can be handled by different subscribers.
The batch class needs to implement the Database.RaisesPlatformEvents interface in order to fire the platform event.
global class SK_AccountProcessBatch implements Database.Batchable<sObject>, Database.RaisesPlatformEvents {
// batch logic
}
Q186. What if you change the name of the execute method to execute1 in the batch class? Will the batch job still run?
No. Go ahead and change execute to execute1 and try saving the class.
Output:
Class batchUpdateAccountsContacts must implement the method: void Database.Batchable<SObject>.execute(Database.BatchableContext, List<SObject>)
Finding: it won't let you save the batch class, as it says the class must implement the execute method.
Q187. What is the upper limit of the scope parameter if the batch class returns an iterable?
If the start method of the batch class returns an iterable, the scope parameter value has no upper limit. However, if you use a high number, you can run into other limits.
Q188. Count the “Customer - Direct” account records processed by the batch class.
Batch Apex is stateless by default. That means for each execution of your execute method, you receive a fresh copy of your object. All fields of the class are initialized, static and instance. If your batch process needs information that is shared across transactions, one approach is to make the Batch Apex class itself stateful by implementing the Database.Stateful interface.
global class AccountBatchApex implements Database.Batchable<sObject>, Database.Stateful {
global integer numberofDirectCustomers = 0;
global Database.QueryLocator start(Database.BatchableContext bc){
String soqlQuery = 'SELECT Name, AccountNumber, Type From Account';
return Database.getQueryLocator(soqlQuery);
}
global void execute(Database.BatchableContext bc, List<Account> scope){
for (Account acc : scope){
if(acc.Type.equals('Customer - Direct')){
numberofDirectCustomers++;
}
}
}
global void finish(Database.BatchableContext bc){
}
}
Q189. Give an example of a Batch Apex class for deleting records.
public class BatchDelete implements Database.Batchable<sObject> {
public String query;
public Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);
}
public void execute(Database.BatchableContext BC, List<sObject> scope){
delete scope;
DataBase.emptyRecycleBin(scope);
}
public void finish(Database.BatchableContext BC){
}
}
Q190. Update the account description, number of employees and contact last name using batch Apex. Get the failure record IDs in an email. Also schedule the job for every Monday.
global class batchUpdateAccountsContacts implements Database.Batchable <sObject>, Database.Stateful, Schedulable {
global batchUpdateAccountsContacts(){
}
Set<id> successRecord = new Set<id>();
Set<id> failRecord = new Set<id>();
global Database.QueryLocator start(Database.BatchableContext info){
String SOQL='Select id,name,NumberOfEmployees, description,(select id, name from contacts) from Account';
return Database.getQueryLocator(SOQL);
}
global void execute(Database.BatchableContext info, List<Account> scope){
List<Account> accsToUpdate = new List<Account>();
List<Contact> cUpdate = new List<Contact>();
for(Account a : scope)
{
a.description ='Test';
a.NumberOfEmployees = 70;
accsToUpdate.add(a);
for (Contact c:a.contacts){
c.lastname = 'test+a';
cUpdate.add(c);
}
}
Database.SaveResult[] srList = Database.update(accsToUpdate, false);
Database.SaveResult[] srList1 = Database.update(cUpdate, false);
for (Database.SaveResult sr : srList) {
if (sr.isSuccess()) {
// Operation was successful, so get the ID of the record that was processed
successRecord.add(sr.getId());
}
else {
for(Database.Error err : sr.getErrors()) {
}
failRecord.add(sr.getId());
}
}
for (Database.SaveResult sr : srList1) {
if (sr.isSuccess()) {
successRecord.add(sr.getId());
}
else {
for(Database.Error err : sr.getErrors()) {
}
failRecord.add(sr.getId());
}
}
}
global void finish(Database.BatchableContext info){
// Get the ID of the AsyncApexJob representing this batch job
// from Database.BatchableContext.
// Query the AsyncApexJob object to retrieve the current job's information.
AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
TotalJobItems, CreatedBy.Email FROM AsyncApexJob WHERE Id = :info.getJobId()];
// Send an email to the Apex job's submitter notifying of job completion.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {a.CreatedBy.Email};
mail.setToAddresses(toAddresses);
mail.setSubject('Account and contact update' + a.Status);
mail.setPlainTextBody
('The batch Apex job processed ' + a.TotalJobItems +
' batches with '+ a.NumberOfErrors + ' failures.'+successRecord+'successRecordids: '+ 'failRecordids: '+ failRecord);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
global void execute(SchedulableContext SC){
database.executeBatch(new batchUpdateAccountsContacts(),100);
// for cron expression
// String cronexpression = '0 0 0 ? * * *'
// System.schedule('Testing', cronexpression, testobj);
}
}
Q191. What is a batch job in Salesforce?
A Batch Apex class is used to process millions of records within normal processing limits. With Batch Apex you process records asynchronously to stay within platform limits. If you have a lot of records to process - for example data cleansing or archiving - Batch Apex is usually the best solution. In Batch Apex each transaction (each execute call) starts with a new set of governor limits, making it easier to ensure your code stays within the governor execution limits.
Q192. What is the difference between stateful and stateless batch jobs?
Stateful Batch Apex: if your batch process needs information shared across transactions, make the batch class stateful by implementing Database.Stateful. This instructs the platform to preserve the values of your static and instance variables between transactions.
global class SummarizeAccountTotal implements Database.Batchable<sObject>, Database.Stateful {
}
In short, if you need to send an email reporting how many records passed and failed in the batch job, you keep the counter in a stateful batch job. If you want one counter created and shared across each execute method, use Database.Stateful.
Stateless Batch Apex: Batch Apex is stateless by default. That means for each execution of the execute method you receive a fresh copy of your object - all fields of the class are re-initialized, both static and instance.
global class SummarizeAccountTotal implements Database.Batchable<sObject> {
}
Q193. Within what timeframe will an asynchronous request be processed after being enqueued?
Asynchronous processing has a lower priority than real-time interaction through the browser and the API, so it always runs in the background when resources are available to process asynchronous jobs. You cannot determine exactly when the job will run - it is determined by the server and the queue depth. It can be immediate, or it can be delayed.
Q194. 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?
A future method can call ordinary (non-future) methods and use their return values normally within its own transaction - including callouts, if the future method is annotated @future(callout=true). What is not allowed is calling another future method from a future method; future methods cannot chain into other future methods (or be called from batch execute).
Q195. Are synchronous web service callouts supported by Scheduled Apex?
No, a scheduled Apex class cannot make a synchronous web service callout directly from the execute method of the Schedulable interface. However, if the Scheduled Apex calls a Batch Apex job (which implements Database.AllowsCallouts) and that job makes the callout, the callout is supported. The same applies to enqueuing a queueable job that allows callouts, or invoking a @future(callout=true) method.
Q196. Why are sObject parameters not supported in future methods?
An sObject might change between the time the future method is called and the time it actually executes. If sObjects could be passed as arguments, the future method would work with the old sObject values held in memory and might overwrite newer values that were saved in the meantime. That is why sObjects cannot be passed as arguments to future methods - instead you pass record Ids and re-query the current values inside the method.
Also noted:
Objects can't be passed as arguments to future methods because the object can change between the time you call the method and the time that it actually executes. Remember, future methods are executed when system resources become available. In this case, the future method may have an old object value when it actually executes, which can cause all sorts of bad things to happen.
Q197. Can I chain a job that implements Database.AllowsCallouts from a job that doesn't?
Yes. Callouts are also allowed in chained queueable jobs - the chained job's own interfaces determine what it may do, so a queueable that implements Database.AllowsCallouts can be enqueued from a queueable that does not, and can then perform callouts.
Q198. In which scenario can we not call a future method from a batch job?
Calling a future method is not allowed from the execute method of a batch job (nor from start or finish). However, a web service can be called from execute, and a web service can in turn call an @future method. So you can define a web service that invokes a future method and call that web service from the execute method of the batch job.
Q199. How does a future method help in avoiding Mixed DML errors?
There are 2 kinds of sObjects in Salesforce:
1. Non-setup objects - Account, Opportunity, custom objects, etc.
2. Setup objects - User, Group, Queue, Permission Set Assignment, etc.
If you perform DML on both kinds of sObject in a single transaction, the system does not allow it and throws a Mixed DML exception, stating that a transaction cannot have a mixture of setup and non-setup DML operations.
To resolve this error, put the DML operation of one kind into a future method's scope. Because the two DML operations are then isolated from each other in separate transactions, the transaction does not fail.
Q200. We run an Apex batch to process 2000 records with a batch size of 200. While doing DML on the 298th record an error occurs. What happens?
In batches, if the first transaction succeeds but the second fails, the database updates made in the first transaction are not rolled back.
Since the batch size is 200, the first batch (records 1-200) is processed completely and all its data is committed to the database.
In the second batch, if you commit records with normal DML statements such as insert or update, the whole batch is rolled back, so records 201 to 400 are not processed.
If you use the Database DML methods such as Database.insert(records, false) with allOrNone set to false, a partial commit can happen: only the 298th record fails, 199 of the 200 records in that batch are processed, and the remaining batches continue to execute normally.
Q201. What is Database.QueryLocator and Iterable<sObject> in Batch Apex?
Database.QueryLocator - you use a simple SOQL SELECT query to generate the scope of objects. The governor limit on the total number of records retrieved by SOQL queries is bypassed, so it can return up to 50 million records.
Iterable<sObject> - you create a custom scope for processing that would not be possible to build with SOQL WHERE clauses. With an iterable, the governor limit on the total number of records retrieved by SOQL queries (50,000) is still enforced.
Q202. What is the difference between batch Apex, future methods and queueable Apex?
Asked at: Mahindra & Mahindra
Future methods @future)
A static void method annotated with @future, used to run work in a separate asynchronous thread - typically callouts from a trigger (@future(callout=true)) and to avoid mixed DML errors.
Parameters must be primitives or collections of primitives - you cannot pass sObjects.
You cannot call a future method from another future method, and a future method cannot be chained or monitored.
Limit: 50 future calls per transaction.
Queueable Apex implements Queueable)
Started with System.enqueueJob(new MyJob()), which returns a job Id you can monitor in AsyncApexJob.
Accepts non-primitive types (sObjects, custom classes) as member variables.
Supports chaining - one queueable job can enqueue another from its execute() method.
Limit: 50 jobs added to the queue per transaction. This is the option to use when 50 future calls are not enough.
Batch Apex implements Database.Batchable<sObject>)
Three methods: start() returns the scope (a Database.QueryLocator of up to 50 million records or an Iterable), execute() processes each chunk (default batch size 200), finish() runs post-processing such as sending a summary email or chaining another batch.
Each execute() chunk gets a fresh set of governor limits, which is why batch Apex is used for very large data volumes.
Up to 5 batch jobs can run concurrently; Database.executeBatch() can queue up to 100 held jobs and the flex queue holds the rest.
Implement Database.AllowsCallouts to make callouts and Database.Stateful to keep state across the chunks.
Scheduled Apex (implements Schedulable) is the fourth option and is used to run any of the above at a given time.
Q203. Can you give an example of Queueable Apex?
Asked at: Mahindra & Mahindra
Answer supplied - source left blank.
A Queueable class implements the Queueable interface and is submitted with System.enqueueJob(), which returns the AsyncApexJob Id for monitoring.
public class AsyncExecutionExample implements Queueable {
public void execute(QueueableContext context) {
// Your processing logic here
// Chain this job to the next job by submitting the next job
System.enqueueJob(new SecondJob());
}
}
// Enqueue it
Id jobId = System.enqueueJob(new AsyncExecutionExample());
Add Database.AllowsCallouts to the class if the job must make an HTTP callout.
It accepts non-primitive members (sObjects, custom types) unlike future methods.
Up to 50 jobs can be added to the queue in a single transaction. For chaining, a running queueable can enqueue only one child job, and the maximum stack depth is 5 in Developer Edition and Trial orgs (no documented depth limit in other editions), and only one job can be chained from a running job.
Q204. How many future methods can we write in a class?
Asked at: GenPact
50 - up to 50 future method invocations are allowed per Apex transaction (the same limit is quoted as the number of @future calls per class/transaction).
Q205. Where do you use Database.AllowsCallouts?
Asked at: Cloud 360
Answer supplied - source left blank.
Database.AllowsCallouts is a marker interface added to an asynchronous Apex class so that the job is allowed to make HTTP/web-service callouts.
public class MyJob implements Queueable, Database.AllowsCallouts {
public void execute(QueueableContext ctx) {
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:My_Named_Credential/data');
req.setMethod('GET');
HttpResponse res = h.send(req);
}
}
Used with Queueable Apex and with Batch Apex (global class X implements Database.Batchable<sObject>, Database.AllowsCallouts).
The equivalent for a future method is the annotation @future(callout=true).
Limit: 100 callouts per transaction; in Batch Apex the callout limit applies per execute() invocation.
Also noted:
Database.AllowsCallouts signals to the Salesforce platform that the code within the class might make outbound HTTP requests. If you are making HTTP callouts from within a Batch Apex class, the class must implement Database.AllowsCallouts.
Q206. How many methods are there in a schedulable class?
Asked at: Cloud 360
Answer supplied - source left blank.
One. A schedulable class implements the Schedulable interface, which declares a single method:
global class ScheduledBatchable implements Schedulable {
global void execute(SchedulableContext sc) {
BatchClass b = new BatchClass();
Database.executeBatch(b);
}
}
It is scheduled from Setup > Apex Classes > Schedule Apex, or with System.schedule('Job name', cronExpression, new ScheduledBatchable());. A maximum of 100 scheduled Apex jobs can be active at a time.
Q207. How many methods are there in a Queueable class?
Asked at: Cloud 360
Answer supplied - source left blank.
One. The Queueable interface declares a single method:
public class AsyncExecutionExample implements Queueable {
public void execute(QueueableContext context) {
// processing logic
}
}
It is submitted with Id jobId = System.enqueueJob(new AsyncExecutionExample());, which returns the AsyncApexJob Id so the job can be monitored. (Compare Batch Apex, which has three methods: start(), execute() and finish().)
Q208. What is a Batch class, what are its functions, and what is the use of the Stateful interface in a batch class?
A batch class implements Database.Batchable<sObject> and has three methods: start() (returns a Database.QueryLocator or an Iterable), execute() (processes each scope of records), and finish() (post-processing).
The Database.Batchable interface can be combined with the Database.Stateful interface to maintain state across batches. By default, batch classes are stateless, meaning they do not retain variable values between batch executions. When you implement Database.Stateful, the instance variable values persist across batch executions - useful for running totals, counters, and collecting errors to report in finish().
Q209. What is the Apex Scheduler?
The Apex Scheduler invokes an Apex class to run at a specific time.
Anybody who wants to schedule their class has to implement the Schedulable interface.
Schedulable interface: The class that implements this interface can be scheduled to run at different intervals. This interface has the method:
public void execute(SchedulableContext sc)
Example:
public class MySchedule implements Schedulable {
public void execute(SchedulableContext sc) {
Account a = new Account(Name = 'Faraz');
insert a;
}
}
Q210. How do you invoke a Batch Apex job programmatically?
We can use the Database.executeBatch() method to programmatically begin the batch job.
Syntax:
public static ID executeBatch(sObject className)
public static ID executeBatch(sObject className, Integer scope)
The above two methods are static methods of the Database class. We can use either one of the methods to execute the batch job.
Note: The class name that we are passing to the Database.executeBatch() method should be an object of the class which has implemented the Database.Batchable interface.
Also noted:
You can also optionally pass a second scope parameter to specify the number of records that should be passed into the execute method for each batch.
Q211. Can we call a Batch Apex job from a trigger?
Asked at: Accenture
Yes, you can call Database.executeBatch() from a trigger, but it is not a best practice - a trigger can fire many times in one transaction and you will quickly hit the limit of 5 queued/active batch jobs (and the 100 async calls per transaction limit), causing governor limit errors.
Q212. Write an example of a Batch Apex class.
global class batchExample implements Database.Batchable<sObject> {
global Database.QueryLocator start(Database.BatchableContext BC) {
String query = 'SELECT Id, Name FROM Account';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Account> accList) {
for (Account acc : accList) {
// Update the Account Name
acc.Name = acc.Name + 'Webkul';
}
try {
// Update the Account Record
update accList;
} catch (Exception e) {
System.debug(e);
}
}
global void finish(Database.BatchableContext BC) {
// execute any post-processing operations
}
}
It is run with Database.executeBatch(new batchExample(), 200);
Q213. How do you use an Iterable instead of a QueryLocator in Batch Apex?
In Batch Apex the start method normally returns a Database.QueryLocator, but you can return an Iterable instead. If your code accesses external objects and is used in Batch Apex, you must use Iterable<sObject> rather than Database.QueryLocator.
global class batchClass implements Database.Batchable<Contact> {
global Iterable<Contact> start(Database.BatchableContext info) {
return new CustomIterable();
}
global void execute(Database.BatchableContext info, List<Contact> scope) {
List<Contact> conToUpdate = new List<Contact>();
for (Contact c : scope) {
c.LastName = 'Test123';
conToUpdate.add(c);
}
update conToUpdate;
}
global void finish(Database.BatchableContext info) {
}
}
Note that with an Iterable the governor limit on records retrieved is the normal 50,000, not the 50 million a QueryLocator allows.
Also noted:
Return an Iterable from start() when the records cannot be produced by a simple SOQL query - for example aggregate results, or data that comes from a callout or a custom iterator. The trade-off is that a QueryLocator can return up to 50 million records, whereas an Iterable is bounded by the normal query-rows governor limit.
Q214. Write an example of a future method.
@future
public static void processRecords(List<ID> recordIds) {
// Get those records based on the IDs
List<Account> accts = [SELECT Name FROM Account WHERE Id IN :recordIds];
// Process records
}
The method must be
static, must returnvoid, and can only take primitive types (or collections of primitives) as parameters - not sObjects.Use @future(callout=true) if the method needs to make a web service callout.
Q215. Write an example of a Schedulable Apex class.
global class scheduledBatchable implements Schedulable {
global void execute(SchedulableContext sc) {
batchable b = new batchable();
Database.executeBatch(b);
}
}
Schedule it from Setup > Apex Classes > Schedule Apex, or from Apex with a CRON expression:
System.schedule('Nightly job', '0 0 2 * * ?', new scheduledBatchable());
A maximum of 100 scheduled Apex jobs can be active at one time.
Q216. How can you set the batch size in batch Apex?
Use the optional scope parameter of Database.executeBatch(batchApexInstance, batchSize).
Id batchProcessId = Database.executeBatch(myBatchApexClass, 200);
In this example the batch size is set to 200.
Q217. What is the maximum number of batch Apex jobs that can be concurrently in an active or queued state?
There can only be 5 batch Apex jobs concurrently in an active or queued state as of today.
Q218. How many @future method invocations are allowed per Apex transaction?
50 future method invocations are allowed per Apex transaction.
Q219. How do you track the progress of a scheduled job in Apex?
Query the CronTrigger object, and its related CronJobDetail, for the job Id.
ctx.getTriggerId() inside execute() gives you the current job Id.
CronTrigger holds scheduling information such as TimesTriggered and NextFireTime.
CronJobDetail holds the job's name and type, and is reached through the CronTrigger.CronJobDetail relationship.
CronTrigger ct = [SELECT TimesTriggered, NextFireTime FROM CronTrigger WHERE Id = :jobID];
CronJobDetail ctd = [SELECT Id, Name, JobType FROM CronJobDetail
WHERE Id = :ct.CronJobDetail.Id];
For batch and queueable jobs, query AsyncApexJob instead:
ID batchprocessid = Database.executeBatch(reassign);
AsyncApexJob aaj = [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors
FROM AsyncApexJob WHERE Id = :batchprocessid];
Q220. How many scheduled (schedulable) Apex jobs can you have at one time?
You can have up to 100 scheduled Apex jobs at one time in the org.
Q221. What is the difference between Database.QueryLocator and Iterable in batch Apex?
A Database.QueryLocator can return millions of rows for a batch (it bypasses the normal SOQL row limit), whereas an Iterable can only pull in as many records as the synchronous query limit allows. Use an Iterable if you want to build the record set with custom logic (without a plain SOQL filter), and use QueryLocator when the records can be selected by a SOQL query with a filter.
Also noted:
QueryLocator can be used when the data that needs to be executed in the batch can be fetched using a query. It has a limit of 50 million records.
When records cannot be filtered by SOQL and the scope is based on some custom business logic, then we go for Iterable. It has a limit of 50K records.
With a QueryLocator object, the governor limit for the total number of records retrieved by SOQL queries is bypassed and you can query up to 50 million records. However, with an Iterable, the governor limit for the total number of records retrieved by SOQL queries is still enforced.
Q222. When would you use a future method, and what are its restrictions and limits?
Use a future method when:
You have a long-running method and need to prevent delaying an Apex transaction.
You make callouts to external web services from a context where callouts are not permitted (for example a trigger) - annotate with @future(callout=true). callout=false is the default.
You need to segregate DML operations and bypass the mixed DML save error. Setup objects (users, profiles, page layouts, permission sets) and non-setup objects (standard and custom objects) cannot be updated in the same transaction; doing the second DML in a future method solves it.
It is a "set it and forget it" method - you call it and the async job is launched.
Restrictions:
The method must be static and return void.
Arguments may only be primitives (Integer, String, and so on) or collections of primitives (List, Map, Set). SObjects and Apex objects are not allowed - serialize them with JSON.serialize() and pass a String instead. (An Id passed as a String is fine.)
You cannot chain @future calls - a future method cannot be called from another future method.
There is no way to monitor the job (no job Id is returned).
It is good practice to group similar external web service calls into a single @future method.
Limits:
50 @future calls per Apex transaction.
No more than 250,000 future calls per 24 hours, or the number of licences multiplied by 200, whichever is greater (the notes quote the older 200-per-licence figure).
Q223. Write an Apex class that sends an SMS through an external web service asynchronously so it can be called from a trigger.
public class SMSUtils {
// Call async from triggers, etc, where callouts are not permitted.
@future(callout=true)
public static void sendSMSAsync(String fromNbr, String toNbr, String m) {
String results = sendSMS(fromNbr, toNbr, m);
System.debug(results);
}
// Call from controllers, etc, for immediate processing
public static String sendSMS(String fromNbr, String toNbr, String m) {
// Calling 'send' will result in a callout
String results = SmsMessage.send(fromNbr, toNbr, m);
insert new SMS_Log__c(to__c = toNbr, from__c = fromNbr, msg__c = results);
return results;
}
}
The synchronous sendSMS method holds the real logic and can be called directly from a controller. The @future(callout=true) wrapper exists so triggers - which cannot make callouts inline - can invoke the same logic on a separate thread. Note that only primitives are passed as arguments, as required by @future.
Q224. How do you write and schedule a Scheduled Apex class?
The class implements the Schedulable interface and contains a single method: global void execute(SchedulableContext ctx) { }.
Run it with System.schedule('job name', cronExpression, new MyClass());, or from Setup > Schedule Jobs / Setup > Apex Classes.
Abort a scheduled job with System.abortJob(jobId).
System.schedule returns a CronTrigger Id.
An easier way to schedule a batch job is System.scheduleBatch(), which avoids having to implement Schedulable at all.
The cron expression has seven fields: seconds minutes hours day_of_month month day_of_week optional_year.
Seconds 0-59, Minutes 0-59, Hours 0-23
Day_of_month 1-31, or *, or ? (no value)
Month 1-12 or * or ?
Day_of_week 1-7 or SUN-SAT, or *, or ?
Year 1970-2099
You cannot specify day-of-month and day-of-week concretely at the same time - one of them must be ?.
Examples:
// Run at 30 minutes past midnight on Jan 1 every year
GeocodingSchedulable cls = new GeocodingSchedulable();
System.schedule('Geocode on Jan 1', '0 30 0 1 1 ? *', cls);
// '0 0 0 * * ?' represents every day at 12 A.M.
// '0 10 17 ? * MON-FRI' runs at 5:10 P.M. Monday to Friday
Limits: 100 scheduled Apex jobs at one time, and a maximum of 250,000 scheduled Apex executions per 24-hour period. Note that the Lightning UI cannot set minutes and seconds - only an Apex cron expression can.
Q225. Write a Schedulable Apex class that verifies its own CronTrigger details and updates a record when it fires.
global class TestScheduledApexFromTestMethod implements Schedulable {
// This test runs a scheduled job at midnight Sept. 3rd. 2022
public static String CRON_EXP = '0 0 0 3 9 ? 2022';
global void execute(SchedulableContext ctx) {
CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime
FROM CronTrigger WHERE Id = :ctx.getTriggerId()];
System.assertEquals(CRON_EXP, ct.CronExpression);
System.assertEquals(0, ct.TimesTriggered);
System.assertEquals('2022-09-03 00:00:00', String.valueOf(ct.NextFireTime));
Account a = [SELECT Id, Name FROM Account WHERE Name = 'testScheduledApexFromTestMethod'];
a.Name = 'testScheduledApexFromTestMethodUpdated';
update a;
}
}
Schedule it with System.schedule('Test job', TestScheduledApexFromTestMethod.CRON_EXP, new TestScheduledApexFromTestMethod());.
Q226. What is Queueable Apex and what advantages does it have over future methods?
Use Queueable Apex to start a long-running operation and get an Id for it, to pass complex types to a job, and to chain jobs.
The class implements the Queueable interface and has a single method: public void execute(QueueableContext context) { }.
Run it with System.enqueueJob(new MyQueueable());, which returns an AsyncApexJob Id, so the job is monitorable and abortable.
Suited to extensive database operations or external web service callouts (implement Database.AllowsCallouts for callouts).
Advantages over future methods:
You get the Id of the new job: ID jobID = System.enqueueJob(new AsyncExecutionExample());. Use this Id to identify the job and monitor its progress in Setup or by querying AsyncApexJob.
Non-primitive types are supported - the queueable class can contain member variables of non-primitive data types such as sObjects or custom Apex types, and those objects are available when the job executes.
Jobs can be chained: you can start a second job from a running job.
Like future jobs, queueable jobs don't process batches, so the number of processed batches and total batches are always zero.
Limits:
You can add up to 50 jobs to the queue with System.enqueueJob in a single transaction. In an asynchronous transaction (for example from a batch Apex job) you can add only one.
Limits.getQueueableJobs() tells you how many queueable jobs have been added.
The maximum stack depth for chained jobs is 5 (Developer Edition and Trial orgs), and only one child job can exist for each parent queueable job.
Q227. Write a Queueable Apex class and show how to chain a second job from it.
A simple queueable job:
public class AsyncExecutionExample implements Queueable {
public void execute(QueueableContext context) {
Account a = new Account(Name = 'Acme', Phone = '(415) 555-1212');
insert a;
}
}
// Enqueue it and keep the job Id for monitoring
ID jobID = System.enqueueJob(new AsyncExecutionExample());
Chaining - submit the second job from the execute() method of the first:
public class AsyncExecutionExample implements Queueable {
public void execute(QueueableContext context) {
// Your processing logic here
// Chain this job to the next job by submitting the next job
System.enqueueJob(new SecondJob());
}
}
You can't chain queueable jobs in an Apex test - doing so results in an error. To avoid it, check whether Apex is running in a test context with Test.isRunningTest() before chaining.
Q228. What is Batch Apex, what methods must it implement, and what are its key limits?
Use Batch Apex for long-running jobs with large data volumes that need to be processed in batches (for example database maintenance jobs), and for jobs that need larger query results than regular transactions allow.
The class implements Database.Batchable<sObject> and has three methods:
global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) - collects the records or objects to pass to execute(). Use Database.QueryLocator to return up to 50 million records; use Iterable<sObject> for custom processing or for aggregate results, which QueryLocator does not support.
global void execute(Database.BatchableContext bc, List<sObject> scope) - processes each batch. Batches tend to execute in the order in which they are received from start, but the order of execution is not guaranteed.
global void finish(Database.BatchableContext bc) - executed after all batches are processed (send emails, chain another job, and so on).
Other points:
Start it with Database.executeBatch(new MyBatch()), optionally with a scope size: Database.executeBatch(new MyBatch(), 100). It returns an AsyncApexJob Id, so the job is monitorable (Setup > Apex Jobs) and abortable.
Default scope size is 200; maximum is 2,000.
Implement Database.Stateful to maintain state between batch transactions; implement Database.AllowsCallouts to make callouts.
Each batch is a separate transaction with a fresh set of governor limits. If the first transaction succeeds but the second fails, the database updates made in the first are not rolled back.
Limits:
5 active or queued batch jobs at a time; up to 100 batch jobs can be held in the Apex flex queue. If the flex queue already holds 100 jobs, Database.executeBatch throws a LimitException.
The start method can have up to 15 query cursors open at a time per user; execute and finish each have a limit of 5 open query cursors per user.
A maximum of 50 million records can be returned, otherwise the job fails.
start, execute and finish can each perform up to 100 callouts.
Only one batch Apex job's start method can run at a time in an org.
A batch job can be called from a trigger and can be scheduled with the Apex scheduler or the Schedule Apex page.
Q229. Write a Batch Apex class that reads yesterday's billing summary records and inserts payout records with the correct slab percentage and GST.
global class DailyPayoutRecordsBatch implements Database.Batchable<SObject> {
global static Database.QueryLocator start(Database.BatchableContext start) {
String query = 'SELECT Id, Patient__c, Admission_Acknowledgement__r.Name, Admission_Acknowledgement__r.Patient_Name__c, Admission_Acknowledgement__r.Max_ID__c,';
query += ' Admission_Acknowledgement__r.Transaction_Type__c, Admission_Acknowledgement__r.IPID__c, Admission_Acknowledgement__r.alletec_hospitallocation__c,';
query += ' Admission_Acknowledgement__r.Discount__c, Admission_Acknowledgement__r.Id, Admission_Acknowledgement__r.OPID__c, Admission_Acknowledgement__r.Last_Number_of_Hours__c FROM Billing_Summary__c';
query += ' WHERE CreatedDate = YESTERDAY AND alletec_isinternational__c = true AND alletec_isbillcancelled__c = false AND HCF_Source__c != NULL AND alletec_transactiontype__c IN (\'IP\',\'OP\',\'Preadmission\')';
System.debug(' within a start query ===>>> ' + query);
return Database.getQueryLocator(query);
}
global static void execute(Database.BatchableContext bt, List<Billing_Summary__c> lst) {
List<Payout__c> payout2insert = new List<Payout__c>();
Map<Id, Map<String, List<Slab_Master__c>>> maphcf2slabmstr = new Map<Id, Map<String, List<Slab_Master__c>>>();
for (Billing_Summary__c billing : lst) {
Payout__c pay = new Payout__c(
Patient_Name__c = billing.Admission_Acknowledgement__r.Patient_Name__c,
Patient__c = billing.Patient__c,
Max_ID__c = billing.Admission_Acknowledgement__r.Max_ID__c,
New_Pre_Intimation_Date_Time__c = billing.Admission_Acknowledgement__r.Pre_Intimation_DateTime__c,
Auto_Tagged__c = billing.Admission_Acknowledgement__r.Auto_Tagged__c,
First_OPD_IPD_Bill_Date__c = billing.Admission_Acknowledgement__r.First_OPD_IPD_Bill_Date__c,
First_OPD_IPD_Bill_No__c = billing.Admission_Acknowledgement__r.First_OPD_IPD_Bill_No__c,
Tagged_On__c = billing.Admission_Acknowledgement__r.Tagged_On__c,
Remarks__c = billing.Admission_Acknowledgement__r.Remarks__c,
Message_Description__c = billing.Admission_Acknowledgement__r.Message_Description__c,
Nationality__c = billing.Nationality__c,
pcl_markuppercentage__c = billing.Admission_Acknowledgement__r.pcl_markuppercentage__c,
alletec_billdate__c = billing.alletec_billdate__c,
invoicenumber__c = billing.invoicenumber__c,
alletec_hisamount__c = billing.alletec_hisamount__c,
Discount__c = billing.Admission_Acknowledgement__r.Discount__c,
Patient_RecordId__c = billing.Admission_Acknowledgement__r.Id,
OPID__c = billing.Admission_Acknowledgement__r.OPID__c,
Number_of_Hours__c = billing.Admission_Acknowledgement__r.Last_Number_of_Hours__c);
if (billing.HCF_Source__r.ParentId != null) {
pay.HCF_Source__c = billing.HCF_Source__r.ParentId;
if (!maphcf2slabmstr.containsKey(billing.HCF_Source__r.ParentId))
maphcf2slabmstr.put(billing.HCF_Source__r.ParentId, new Map<String, List<Slab_Master__c>>());
} else {
pay.HCF_Source__c = billing.HCF_Source__c;
if (!maphcf2slabmstr.containsKey(billing.HCF_Source__c))
maphcf2slabmstr.put(billing.HCF_Source__c, new Map<String, List<Slab_Master__c>>());
}
payout2insert.add(pay);
}
if (maphcf2slabmstr != null && maphcf2slabmstr.size() > 0) {
for (Slab_Master__c slb : [SELECT Id, HCF_Source__c, Minimum_Range__c, Payout_Percent__c, Maximum_Range__c,
Validity__c, GST__c, Location__c
FROM Slab_Master__c
WHERE HCF_Source__c IN :maphcf2slabmstr.keySet()
AND Validity__c >= :System.today() - 1]) {
if (!maphcf2slabmstr.get(slb.HCF_Source__c).containsKey(slb.Location__c))
maphcf2slabmstr.get(slb.HCF_Source__c).put(slb.Location__c, new List<Slab_Master__c>());
maphcf2slabmstr.get(slb.HCF_Source__c).get(slb.Location__c).add(slb);
}
for (Payout__c pay : payout2insert) {
if (maphcf2slabmstr.containsKey(pay.HCF_Source__c) && maphcf2slabmstr.get(pay.HCF_Source__c).size() > 0) {
if (maphcf2slabmstr.get(pay.HCF_Source__c).containsKey(pay.Nationality__c)) {
getPercentInfo(pay, maphcf2slabmstr.get(pay.HCF_Source__c).get(pay.Nationality__c));
} else if (maphcf2slabmstr.get(pay.HCF_Source__c).get('Other') != null
&& maphcf2slabmstr.get(pay.HCF_Source__c).get('Other').size() > 0) {
getPercentInfo(pay, maphcf2slabmstr.get(pay.HCF_Source__c).get('Other'));
}
}
}
if (payout2insert != null && payout2insert.size() > 0)
insert payout2insert;
}
}
global void finish(Database.BatchableContext bt) {
System.debug('finish list ===>>> ' + bt);
}
private static Payout__c getPercentInfo(Payout__c pay, List<Slab_Master__c> slblst) {
Boolean IsIn = false;
for (Slab_Master__c slb : slblst) {
if (slb.Minimum_Range__c != null && slb.Maximum_Range__c != null) {
if (pay.alletec_hisamount__c >= slb.Minimum_Range__c && pay.alletec_hisamount__c <= slb.Maximum_Range__c) {
pay.GST__c = slb.GST__c;
pay.Payout_Percentage__c = slb.Payout_Percent__c;
pay.Slab_Master__c = slb.Id;
IsIn = true;
break;
}
} else if (slb.Minimum_Range__c != null) {
if (pay.alletec_hisamount__c >= slb.Minimum_Range__c) {
pay.GST__c = slb.GST__c;
pay.Payout_Percentage__c = slb.Payout_Percent__c;
pay.Slab_Master__c = slb.Id;
IsIn = true;
break;
}
} else if (slb.Maximum_Range__c != null) {
if (pay.alletec_hisamount__c <= slb.Maximum_Range__c) {
pay.GST__c = slb.GST__c;
pay.Payout_Percentage__c = slb.Payout_Percent__c;
pay.Slab_Master__c = slb.Id;
IsIn = true;
break;
}
} else {
pay.GST__c = slb.GST__c;
pay.Payout_Percentage__c = slb.Payout_Percent__c;
pay.Slab_Master__c = slb.Id;
IsIn = true;
break;
}
}
if (pay.alletec_hisamount__c != null && IsIn == true) {
pay.Total_Payout__c = pay.alletec_hisamount__c
+ (pay.alletec_hisamount__c * Integer.valueOf(pay.Payout_Percentage__c)) / 100;
pay.Total_Payout__c += (pay.Total_Payout__c * pay.GST__c) / 100;
}
return pay;
}
}
Points worth calling out in an interview: the query is built as a string and returned through Database.getQueryLocator, all related slab records are fetched once into a nested map (keyed by HCF source and then location) so there is no SOQL inside the loop, and the DML is done once per batch on a list.
Q230. What is the difference between a future method and a Queueable job?
Job Id: System.enqueueJob() returns an AsyncApexJob Id so a Queueable job can be monitored in Setup or by SOQL, and aborted. A future method returns nothing and cannot be monitored.
Parameters: a future method only accepts primitives and collections of primitives, so sObjects must be serialized to JSON. A Queueable class is an object, so it can hold member variables of any type, including sObjects and custom Apex types.
Chaining: a Queueable job can enqueue another job from its execute() method (up to a stack depth of 5, one child per parent). Future methods cannot be chained or called from each other.
Callouts: both support callouts - @future(callout=true) for future methods, implements Database.AllowsCallouts for Queueable.
Both run asynchronously with higher governor limits, and neither processes records in batches.
In practice, Queueable is the modern replacement for future methods; use @future mainly for simple fire-and-forget work or where a legacy pattern already exists (for example bypassing mixed DML).
Also noted:
Queueable Apex is similar to future methods in that both are queued for execution, but Queueable Apex provides these additional benefits:
When you queue a Queueable Apex job, you get a job ID that can be used to trace it easily, which is not possible with future methods.
You can use non-primitive data types in Queueable Apex, like objects and sObjects, which is not possible with future methods, because they support only primitive data types as parameters.
You can chain jobs, by starting a second job from a running job, which is not possible with future methods, because we can't call another future method from a future context.
Apex - Core, Triggers & Governor Limits
107 questions
Q231. Create three account records, one with missing required information. Once the code is executed, two records should be saved to the database and the one record which is not saved should print an error.
Account[] accts = new List<Account>{
new Account(Name='Account1'),
new Account(),
new Account(Name='Account3')
};
Database.SaveResult[] sr = Database.insert(accts, false);
for (Database.SaveResult sr : sr) {
if (sr.isSuccess()) {
// Operation was successful, so get the ID of the record that was processed
System.debug('Successfully inserted account. Account ID: ' + sr.getId());
}
else {
for(Database.Error err : sr.getErrors()) {
system.debug('err'+err);
System.debug('The following error has occurred.');
System.debug(err.getStatusCode() + ': ' + err.getMessage());
System.debug('Account fields that affected this error: ' + err.getFields());
}
}
}
Q232. When should Apex be used over Workflow Rules or Process Builder?
There are various reasons to use Apex over declarative automation:
Workflow rules and Process Builder sometimes have feature limitations that can be overcome with Apex - for example pulling information from an external system (callouts).
When dealing with complex logic or large sets of data, Apex can be more efficient than declarative options because it has fewer limitations and can be bulkified and tuned.
Apex supports proper error handling, rollback with savepoints, recursion control and unit testing.
Q233. What is an Apex Email Service?
Email services let you process the contents, headers and attachments of inbound email. You write an Apex class that implements the Messaging.InboundEmailHandler interface, and Salesforce generates an email service address; anything sent to that address is passed to your class. For example, you can create an email service that automatically creates Contact records based on contact information in the messages.
Also noted:
You can associate each email service with one or more Salesforce-generated email addresses to which users can send messages for processing.
Q234. What are the different types of collections you can have in Apex?
There are three main types of collections:
Lists - an ordered collection of elements distinguished by their indices. List elements can be of any data type - primitive types, collections, sObjects, user-defined types and built-in Apex types.
Sets - an unordered collection of elements that does not contain duplicates. Set elements can be of any data type - primitive types, collections, sObjects, user-defined types and built-in Apex types.
Maps - a collection of key-value pairs where each unique key maps to a single value. Keys and values can be any data type - primitive types, collections, sObjects, user-defined types and built-in Apex types.
Q235. What is a wrapper class in Apex and when do you use it?
A wrapper (or container) class is a class, a data structure or an abstract data type that holds different objects or collections of objects as its members.
It is typically an inner class with a few public properties, populated through a constructor, for example a Boolean isSelected plus an sObject, so that a Visualforce page or Lightning component can show a checkbox next to each record.
It is also used to shape data for serialization: JSON.serialize(List<Account>) produces JSON, and JSON.deserialize(jsonString, List<WrapperClass>.class) converts an API response into a typed list, where the wrapper's fields must have exactly the same names as the keys in the response.
For a response whose fields are not known in advance you can deserialize dynamically into a Map<String, Object> using JSON.deserializeUntyped().
Example:
public class AccountWrapper {
public Account acc { get; set; }
public Boolean isSelected { get; set; }
public AccountWrapper(Account a) {
this.acc = a;
this.isSelected = false;
}
}
Typical use: bind isSelected to a checkbox column in a Visualforce page or Lightning table so the user can pick rows, then loop the wrapper list in the controller and act only on the selected records.
Q236. What is an Apex transaction?
An Apex transaction is a set of operations executed as a single unit. These operations include DML operations and the queries that fetch records.
All the DML operations in a transaction either complete successfully or are completely rolled back if an error occurs - even if the error happens while saving a single record. Governor limits are also reset at the start of each transaction.
Q237. What are the different ways to invoke Apex code?
The various ways to call an Apex class in Salesforce are:
Developer Console (anonymous Apex)
Triggers
Visualforce pages (controllers and extensions)
JavaScript links / buttons
Home page components
Another Apex class
Lightning components (@AuraEnabled methods), flows (@InvocableMethod), REST/SOAP web services and scheduled/batch jobs
Also noted:
Through a DML operation that fires a trigger
By scheduling an Apex class that implements the Schedulable interface (for example to run batch Apex)
By running anonymous Apex through the Developer Console
By associating an Apex class with a Visualforce page as a controller or extension
Q238. What is Trigger.new?
Trigger.new is a context variable that returns the new versions of the sObject records. The sObject list is only available in insert, update and undelete triggers, and the records can be modified only in before triggers. In after triggers the list is read-only.
Also noted:
Trigger.new is the list of records that are in the context of the trigger, i.e. the records whose creation, modification or deletion caused the trigger to fire.
Q239. Explain exception catching in a program.
Apex (like Java) has built-in exception handling. The normal code goes into the try block and the exception-handling code goes into the catch block; a finally block runs whether or not an exception occurred. You can chain multiple catch blocks to handle different exception types.
try {
insert acc;
} catch (DmlException e) {
System.debug('DML error: ' + e.getMessage());
} catch (Exception e) {
System.debug('Other error: ' + e.getMessage());
} finally {
// cleanup
}
Q240. Which trigger operation does not have undelete?
The before operation does not have undelete - there is no before undelete trigger event; only after undelete exists.
Q241. What is the use of the Blob variable in Apex?
Blob is a data type meant to collect binary data - for example the body of an attachment, a file or a PDF rendered from a Visualforce page. toString() converts the Blob back into a String, and Blob.valueOf(String) converts the other way. It is also used with Crypto methods and EncodingUtil.base64Encode().
Q242. What are primitive data types in Apex?
Integer, Double, Long, Date, Datetime, String, ID and Boolean (also Decimal, Time and Blob) are the primitive data types. They are passed by value and not by reference.
Q243. What does a data wrapper class contain?
A data wrapper class contains abstract, structured and collection data - it wraps different objects or collections of objects together as its members so that they can be handled as a single unit, for example to display a mixed data set on a page.
Also noted:
A data wrapper class contains a combination of data - it can hold abstract, structured and collection data - grouping fields from one or more objects together, plus any extra attributes required for display or processing.
Q244. Is a return type mandatory for a method in Apex?
Yes - a return type must be declared for every Apex method. If the method returns nothing, the return type is void. (Constructors are the only exception, as they have no return type.)
Q245. How many bits does a Long variable have in Apex?
A Long is a 64-bit number - it ranges from -2^63 to 2^63-1, and is used when a value exceeds the range of an Integer (32-bit).
Q246. Explain the difference between Trigger.old and Trigger.new in Salesforce.
Trigger.old contains the old versions of the records as they were before the update (or the versions being deleted), while Trigger.new contains the new versions of the records with the incoming values. Trigger.old is available in update and delete triggers only, and is always read-only. Trigger.new is available in insert, update and undelete triggers, and is modifiable only in before triggers.
Q247. What is Apex, and when should you use Apex over Flow?
Apex is a programming language developed by Salesforce. It is a strongly typed, object-oriented language that allows developers to execute flow and transaction control statements on the Salesforce platform, running on Salesforce servers alongside calls to the API.
When to use Apex over Flow:
Complex logic, recursion, sophisticated error handling, rollback with savepoints, or dynamic SOQL/metadata work.
Callouts to external systems and complex integration handling.
Large data volumes requiring batch or queueable processing.
A common architectural approach is to separate DML activity and offload it to Apex, and let declarative tools handle non-DML activities like email alerts and in-app alerts - just be careful to ensure your Apex and declarative automation do not conflict or trigger each other recursively.
Q248. What is mixed DML?
A Mixed DML operation error occurs when you try to persist, in the same transaction, changes to a setup object and a non-setup object. For example, updating an Account record and a User record at the same time raises MIXED_DML_OPERATION. Setup objects include User, Group, GroupMember, PermissionSetAssignment and Queue; non-setup objects include Account, Opportunity and custom objects. The fix is to isolate one of the DML operations - typically by moving it into a @future method or a queueable job - or to use System.runAs() in tests.
Q249. What is the use of the Trigger class in Salesforce?
Use the Trigger class to access run-time context information in a trigger - such as the type of trigger that is executing (Trigger.isBefore, Trigger.isInsert) and the list of sObject records the trigger operates on (Trigger.new, Trigger.old, Trigger.newMap, Trigger.oldMap, Trigger.size, Trigger.operationType).
Q250. What are the different events available in triggers?
Answer supplied - source left blank.
Apex triggers support seven events, split between the before and after timing:
before insert
before update
before delete
after insert
after update
after delete
after undelete
An upsert operation fires the insert or update events depending on whether the record exists, and a merge fires delete events on the losing records and update events on the winning record.
Q251. How many times does a trigger execute on an upsert event?
An upsert trigger fires on 4 different events: before insert, before update, after insert and after update - the insert pair for new records and the update pair for existing records.
Q252. How many times does a trigger execute on a merge event?
Merge fires delete triggers (before delete and after delete) on the losing records, and update triggers (before update and after update) on the winning master record. So merge triggers are fired on both events on the delete side, plus the update events on the surviving record.
Q253. When would you choose a before event and when would you choose an after event in a trigger?
Use a before trigger to validate or update fields on the record that fired the trigger, because the record is not yet saved and the changes are persisted without an extra DML statement.
Use an after trigger when you need the record's Id or system fields (for insert), or when you need to create, update or query related or child records, or send a record to an external system - the record is already saved at that point and is read-only in Trigger.new.
Q254. What is the difference between Trigger.new and Trigger.newMap?
Trigger.new returns the list of sObjects that invoked the trigger. Trigger.newMap returns a Map<Id, sObject> of record Id to the new version of the record, which makes it easy to look up a record by Id and to compare with Trigger.oldMap. Trigger.newMap is not available in before insert (no Ids exist yet).
Q255. How do you avoid recursion in a trigger?
There are different ways to stop recursion in a trigger:
Use a static Boolean variable - create a class with a static Boolean variable defaulted to true, check and flip it before running the logic.
This works well for fewer than 200 records.
If you update 200+ records the trigger runs in multiple batches, and the flag means only the first set of records is processed and the others are skipped.
Use a static Set to store record Ids - keep a static Set<Id> in a helper class holding all processed record Ids, and skip records already in the set. This is bulk-safe and is the preferred pattern.
Additional techniques: compare old and new field values so the logic only runs when the relevant field actually changed, and use a static Map of Id to field value to detect real changes.
Q256. Which trigger context variables are available in each trigger event?
Event Trigger.new Trigger.newMap Trigger.old Trigger.oldMap
--- --- --- --- ---
Before Insert Yes No No No
After Insert Yes Yes No No
Before Update Yes Yes Yes Yes
After Update Yes Yes Yes Yes
Before Delete No No Yes Yes
After Delete No No Yes Yes
After Undelete Yes Yes No No
Trigger.new stores the new version of the sObjects (a List). Record ids are not available in the before insert context.
Trigger.old stores the old version of the sObjects - the records being deleted or the values before an update (a List); Trigger.oldMap is the same data as a Map keyed by Id.
Boolean context variables tell you which context you are in: Trigger.isInsert, Trigger.isUpdate, Trigger.isDelete, Trigger.isUndelete, Trigger.isBefore, Trigger.isAfter, plus Trigger.size and Trigger.operationType.
Q257. What are the trigger context variables?
Answer supplied - source left blank.
Trigger context variables give information about the running trigger:
Trigger.isExecuting - true if the current context is a trigger.
Trigger.isInsert, Trigger.isUpdate, Trigger.isDelete, Trigger.isUndelete - the DML operation.
Trigger.isBefore, Trigger.isAfter - the timing.
Trigger.new - list of the new versions of the records (available in insert, update, undelete; read-only in after triggers).
Trigger.old - list of the old versions of the records (available in update and delete).
Trigger.newMap - map of Id to new records (available in before update, after insert, after update, after undelete).
Trigger.oldMap - map of Id to old records (available in update and delete).
Trigger.size - total number of records in the trigger invocation.
Trigger.operationType - the System.TriggerOperation enum value.
Note that Trigger.newMap is not available in before insert, because the records do not yet have Ids.
Q258. How do you serialize and deserialize JSON data in Apex?
Using JSON.serialize() and JSON.deserialize(). JSON.deserializeUntyped() can be used when the structure is not known in advance.
Q259. What do you do when a governor limit is hit? How do you rectify it?
Asked at: Mahindra & Mahindra
Bulkify the code so it handles collections of records rather than one record at a time.
Avoid SOQL queries and DML statements inside for loops.
Bulkify your helper methods as well, not just the trigger.
Use collections - List<>, Set<>, Map<> - for better performance and fewer queries.
Move heavy processing to asynchronous Apex (Batch, Queueable, future) where the limits are higher.
Use the Limits class methods (for example Limits.getQueries()) to check consumption before you exceed a limit.
Q260. What do you do if a SOQL query returns more than 50,000 records?
Asked at: Mahindra & Mahindra
Use Batch Apex, because a simple SOQL query cannot fetch more than 50,000 records in one transaction.
Batch Apex's start() method returns a Database.QueryLocator, which can return up to 50 million records, and the records are handed to execute() in chunks (default scope 200).
Alternatively use a for (Account a : [SELECT ...]) SOQL for loop to process records in batches of 200, which keeps the heap size down (but the 50,000-row limit still applies).
Q261. How do you remove duplicates from a list of records in Apex?
Asked at: Accenture
Put the list into a Set, which does not allow duplicates, then read it back into a list.
Or query with the
GROUP BYclause, which returns unique values directly.
Set<String> unique = new Set<String>();
unique.addAll(myList);
List<String> deduped = new List<String>(unique);
Q262. What are governor limits? Can you name three examples?
Asked at: Accenture
Governor limits are the runtime limits enforced by the Apex runtime engine on Salesforce resources.
Salesforce is multi-tenant - CPU, memory, database and storage are shared - so limits stop any one tenant's code monopolising them.
They are applied per transaction and cannot be exceeded; hitting one throws an uncatchable LimitException.
Examples: 100 SOQL queries (synchronous), 50,000 rows retrieved, 150 DML statements, 10,000 records per DML, 100 callouts, 6 MB heap (12 MB async), 10,000 ms CPU (60,000 ms async).
Q263. Can we call external services from a trigger?
Asked at: Accenture
No - you cannot make a callout directly from a trigger. The callout would hold the database transaction open for the duration of the call, locking records until the transaction completes, so Salesforce blocks it (Callout from a trigger is currently not supported).
Do it asynchronously instead: a @future(callout=true) method, or a Queueable class that implements Database.AllowsCallouts, called from the trigger.
Q264. How do you delete lookup child records when the parent is deleted?
Asked at: Accenture
A lookup relationship does not cascade delete, so use an after delete trigger on the parent: query the children by the lookup field and delete them.
trigger AccountTrigger on Account (after delete) {
delete [SELECT Id FROM Child__c WHERE Account__c IN :Trigger.oldMap.keySet()];
}
(Alternatively, when creating the lookup field, choose Delete this record also as the deletion behaviour where that option is available.)
Q265. How many records can be fetched from a single SOQL transaction?
Asked at: Accenture
50,000 records is the limit for the total number of rows retrieved by SOQL queries in a single Apex transaction. For more than that, use Batch Apex, whose QueryLocator can return up to 50 million records.
Q266. What are the best practices for writing a trigger?
Asked at: Cognizant
One trigger per object.
The trigger itself should contain no business logic - delegate to a handler class.
Bulkify - never assume a single record; use Trigger.new/Trigger.newMap.
Use collections - List, Set, Map - to avoid SOQL and DML inside loops.
Use a context-variable/recursion guard (a static Boolean) to prevent recursive execution.
Avoid hard-coded Ids; use Custom Metadata/Custom Settings.
Handle exceptions and write bulk unit tests (200 records).
Q267. Can you give an example of bulkifying code?
Asked at: Cognizant
Bulkifying means combining repetitive per-record work into a single operation on a collection - the same way a batch class processes a scope of records rather than one at a time.
// Bad - DML and SOQL inside the loop
for (Account a : Trigger.new) {
List<Contact> cons = [SELECT Id FROM Contact WHERE AccountId = :a.Id];
update cons;
}
// Bulkified - one query, one DML
Map<Id, Account> accMap = new Map<Id, Account>(Trigger.new);
List<Contact> toUpdate = [SELECT Id, AccountId FROM Contact WHERE AccountId IN :accMap.keySet()];
for (Contact c : toUpdate) {
c.Description = accMap.get(c.AccountId).Name;
}
update toUpdate;
Also noted:
Bulkifying means combining repetitive tasks so they are performed once for a whole collection instead of once per record - for example collecting IDs in a Set inside the loop, running a single SOQL query outside the loop, and performing a single DML on a List after the loop. The same principle applies when writing a Batch class, where each execute() call receives a scope of records to process together.
Q268. What is the main aim of bulkifying code?
Asked at: Cognizant
To combine repetitive tasks into a single operation and thereby avoid hitting the governor limits - one SOQL query and one DML statement for many records instead of one per record - which also makes the code faster and able to handle bulk loads, Data Loader and API traffic.
Q269. What is the global access modifier used for in Apex?
Asked at: Cloud 360
Answer supplied - source left blank.
global makes a class, method, variable or inner class visible everywhere - including outside the namespace/package in which it is defined.
It is required for anything that must be callable from outside your code: @RestResource REST services, webservice (SOAP) methods, Batch/Schedulable/Queueable classes used in a managed package, and Apex exposed to subscribers of a managed package.
Every method in a global interface/class that is itself exposed must also be global (or webservice).
Once released in a managed package a global member cannot be removed or have its signature changed, so use it sparingly - prefer public inside your own org.
Ordering: private < protected < public < global.
Q270. What is the "Too many SOQL queries: 101" issue in Salesforce?
This is the Salesforce governor limit exception System.LimitException: Too many SOQL queries: 101. It means you can only have up to 100 SOQL queries in a single synchronous transaction. This is a hard limit which cannot be increased by contacting Salesforce support. The limit is 100 SOQL queries in synchronous Apex and 200 in asynchronous Apex. It is usually caused by placing a SOQL query inside a for loop - the fix is to bulkify the code and move the query outside the loop.
Q271. How can you call Apex from Process Builder?
Using the @InvocableMethod annotation on a static Apex method, which then appears as an Apex action in Process Builder (and in Flow).
Q272. What annotation do we use to call Apex from a Flow or Process Builder?
The @InvocableMethod annotation.
Q273. What is Apex?
Apex is a strongly typed, object-oriented programming language that enables developers to add business logic to the Salesforce platform. It runs on Salesforce servers, has a Java-like syntax, and is executed by events such as record changes, button clicks, triggers and web service requests.
Also noted:
Use Apex when you need to:
Create email services.
Create web services.
Perform complex validation over multiple objects.
Create complex business processes that are not supported by workflow.
Create custom transaction logic.
Attach custom logic to another operation.
Apex is the language in which Salesforce code is written. While it is a tool for developers more than admins, it is important to know that code can extend your org to do pretty much anything you need - beyond the limits of point-and-click automation. See the Apex Basics & Database Trailhead module.
Q274. What are the key characteristics of the Apex programming language?
1. Integrated - it provides built-in support for DML calls.
2. Inline Salesforce Object Query Language (SOQL) support.
3. Easy to use.
4. Easy to test.
5. Versioned - code can be saved against different API versions.
6. Multi-tenant aware applications.
Q275. How does Apex work?
All Apex programs run entirely on-demand on the Force.com platform.
First, the platform application server compiles the code into an abstract set of instructions that can be understood by the Apex runtime interpreter.
The compiled code is stored as metadata.
When the end user triggers the execution of Apex - by clicking a button or a Visualforce page - the application server retrieves the compiled instructions from the metadata and sends them to the runtime interpreter before returning the result.
Q276. What is a Map in Apex?
The Map class contains methods for the Map collection type.
A Map is a collection of key-value pairs where each unique key maps to a single value.
Map keys and values can be any data type - primitive types, collections, sObjects, user-defined types and built-in Apex types.
For example, the following table represents a map of countries and currencies:
Country (Key) 'United States' 'Japan' 'France' 'England' 'India'
--- --- --- --- --- ---
Currency (Value) 'Dollar' 'Yen' 'Euro' 'Pound' 'Rupee'
Q277. What is an Apex interface?
An interface is a collection of unimplemented methods. It specifies the signature of the method - the types of inputs that are passed to the method and what type is given as output.
Note: Generally the interface methods are declared as global.
Q278. What are the types of Apex triggers (when can a trigger run)?
Triggers are divided into 2 types:
1. Before triggers - can be used to update or validate values of a record before they are saved to the database.
2. After triggers - can be used to access field values of the records that are stored in the database and use these values to make changes in other records.
Syntax:
trigger trigger_name on Object_Name(trigger_events) {
// Code_block
}
where trigger_events can be a comma-separated list of events.
Also noted:
Before and after - a trigger can be defined for before insert, before update, before delete, after insert, after update, after delete and after undelete (and upsert fires the insert/update events).
Q279. What is the difference between a trigger and a workflow?
Workflow
Workflow is an automated process that fires an action based on evaluation criteria and rule criteria.
We can access a workflow across the object.
We cannot perform DML operations in a workflow.
We cannot query from the database.
Trigger
A trigger is a piece of code that executes before or after a record is inserted or updated.
We can access the trigger across the object and objects related to that object.
DML statements are limited per transaction, not per trigger (150 DML statements).
SOQL queries are limited per transaction, not per trigger (100 queries synchronous, 200 asynchronous).
Q280. How do you detect governor limits through Apex?
First of all, the exception thrown by hitting a limit, System.LimitException, is uncatchable and means that your script will be killed, even if it happens inside a try/catch block.
There is a class, Limits, that contains a number of static methods that allow you to check your governor limit consumption. See the Apex Developer Guide topic on System.Limits methods.
With that said, @future calls per day is one of the limits that simultaneously is and isn't a governor limit, as it throws a System.AsyncException instead, which is not catchable and kills your script as a LimitException would.
Q281. What is a concise function that formats a decimal into a currency format in Apex?
A first version, which handles rounding issues with negative and fractional values (not rendering -0.001 as "-0.00", not rendering -1.10 as "-1.09"):
public static String formatCurrency(Decimal i) {
if (i == null || Math.abs(i) < 0.005) return '$0.00';
String s = (i.setScale(2) + (i >= 0 ? 0.001 : -0.001)).format();
return s.substring(0, s.length() - 1);
}
An improved version that delegates to Math.roundToLong (which uses round-half-even) and passes all unit tests:
private String formatCurrency(Decimal i) {
if (i == null) return '0.00';
i = Decimal.valueOf(Math.roundToLong(i * 100)) / 100;
String s = (i.setScale(2) + (i >= 0 ? 0.001 : -0.001)).format();
return s.substring(0, s.length() - 1);
}
Q282. Is there a de facto third-party utilities library for Apex, such as Apache Commons is for Java?
Apex-lang is about as close to a Java-style library as you can get. It contains several string, database and collection utilities that mimic Java functionality. Be aware, though, that some parts - including comparing and sorting collections - are out of date with the advent of the Comparable interface in Apex.
In addition to apex-lang, it is common to create or reuse static helper methods throughout your projects. Static helper methods are very convenient for reusing code in Chatter functionality, DML handling, exception handling, unit testing, etc.
Q283. What are the recommended ways to refactor in Apex?
A practical approach is to select the 'src' folder in the IDE and use File Search/Replace, so that all the changes are made and saved to the server in one go.
Q284. What is the workaround for the missing Apex Time.format() instance method?
You could split the DateTime.format() result on the first space:
public String myDateFormat(DateTime dt) {
String[] parts = dt.format().split(' ');
return (parts.size() == 3) ? (parts[1] + ' ' + parts[2]) : parts[1];
}
This produces 6:38 PM in English (United States) and 18:42 in French (France).
However, this method is not very robust - some locales may include spaces in the date or time portion of the format, and the ordering is not consistent. This second attempt assumes that the date and time are separated by zero or more spaces, but handles spaces within the two portions and either ordering of date and time. The only assumption made is that the formatted Date is contained within the formatted DateTime:
public String myDateFormat(DateTime dt) {
return dt.format().replace(dt.date().format(), '').trim();
}
This seems to work fine for Hebrew, Vietnamese and Korean, as well as English and French.
Q285. Is there an average method in Apex Math?
No. The standard Math methods only include simpler operations (i.e. those that work on a single value or two values), so you have to roll your own method.
The number of script statements executed will be proportional to the length of the list, so if the lists are ever of a fixed size it could be worth using a macro to generate the addition part for you:
Integer sum = i[0] + i[1] + ... + i[n];
Doing so would only count for one statement, but you'll only need this if governor limits are a concern, which is often not a worry.
If governor limits aren't an issue you could create a function along these lines:
Integer[] myInts = new Integer[]{1, 2, 3, 4, 5, 6, 7};
Integer total = 0;
Double dAvg;
for (Integer i : myInts) {
total += i;
}
dAvg = Double.valueOf(total) / myInts.size();
return dAvg;
Q286. Is there a grammar available for creating an Apex parser?
Salesforce has never published an official Apex grammar. In practice you have these options:
Open-source ANTLR grammars - the apex-parser project (the grammar behind PMD's Apex rules and Salesforce Code Analyzer) is the de-facto community grammar.
Apex Language Server - shipped with the Salesforce Extensions for VS Code; it exposes parsing and symbol information over LSP.
Salesforce Code Analyzer / PMD - if the goal is static analysis rather than building your own parser, use these directly.
Tooling API - generally available and fully documented since Winter '13; it gives you programmatic access to Apex source, symbol tables (SymbolTable on ApexClass) and compilation, which covers most parsing use cases without writing a grammar.
(Note: older versions of this answer said the Tooling API was not yet public. It has been GA since 2012.)
Q287. Does a field's 'default value' do anything if the object is created through Apex?
Default values are not applied automatically when you create an sObject in Apex with the new keyword. You can explicitly load them using:
Foo__c f = Foo__c.sObjectType.newSObject(
recordTypeId, // can be null
true); // loadDefaultValues
Q288. Can you detect the current LoggingLevel in Apex?
No. There is no way to check the current logging level in Apex.
Q289. Can you call an Apex class method on the fly (dynamically)?
While you can instantiate a class based on its name using the Type system class, you can't dynamically locate a method and execute it.
The best that you can do is to dynamically create an instance of a class that implements an interface, and execute one of the methods on the interface. There's more information on the Type class and an example in the Apex Developer's Guide.
Q290. What's the best way to check if person accounts are enabled via Apex code?
There are two methods to accomplish this.
Method 1: Try to access the isPersonAccount property on an Account and catch any exception that occurs if that property is missing. If an exception is generated then person accounts are disabled; otherwise they're enabled. To avoid making person accounts required for the package, assign the Account object to an sObject and use sObject.get('isPersonAccount') rather than accessing that property directly on the Account object. This method takes ~3.5 ms and negligible heap space.
// Test to see if person accounts are enabled.
public Boolean personAccountsEnabled() {
try {
// Try to use the isPersonAccount field.
sObject testObject = new Account();
testObject.get('isPersonAccount');
// If we got here without an exception, return true.
return true;
} catch (Exception ex) {
// An exception was generated trying to access the isPersonAccount field
// so person accounts aren't enabled; return false.
return false;
}
}
Method 2: Use the Account metadata to check whether the isPersonAccount field exists. This is a more elegant method but it executes a describe call which counts towards your governor limits. It's also slightly slower and uses a lot more heap space - it takes ~7 ms and ~100 KB of heap.
// Check to see if person accounts are enabled.
public Boolean personAccountsEnabled() {
// Describe the Account object to get a map of all fields
// then check to see if the map contains the field 'isPersonAccount'
return Schema.sObjectType.Account.fields.getMap().containsKey('isPersonAccount');
}
Q291. How can I tell the day of the week of a date?
Formulas
There isn't a built-in function to do this, but you can figure it out by counting the days since a date you know. For example, June 29, 1985 was a Saturday. To figure out the day of the week of July 9 of that year, subtract the dates to determine the number of days (10), then use modular division to remove all the multiples of 7. The remainder is the number of days after Saturday (1 = Sunday, 2 = Monday, etc.) and you can use that number in your logic:
MOD(DATEVALUE( Date_Field__c ) - DATE(1985,7,1), 7)
Apex code
You could do the same thing with time deltas, but you can also use the poorly documented DateTime.format() function:
// Cast the Date variable into a DateTime
DateTime myDateTime = (DateTime) myDate;
String dayOfWeek = myDateTime.format('E');
// dayOfWeek is Sun, Mon, Tue, etc.
Q292. What is the difference between break and continue in an Apex for loop?
Asked at: Cloud 360
breakexits the loop entirely as soon as it is reached.continueskips the rest of the current iteration and moves on to the next one.
for (Integer counter = 0; counter < 10; counter++) {
if (counter == 4) { break; }
System.debug(counter); // prints 0, 1, 2, 3
}
for (Integer counter = 0; counter < 10; counter++) {
if (counter == 4) { continue; }
System.debug(counter); // prints 0,1,2,3,5,6,7,8,9 - 4 is skipped
}
Q293. What is an Apex class?
An Apex class is a template or blueprint from which objects are created - it is a collection of variables and methods (and optionally constructors, inner classes and properties) that define the business logic. Classes are defined with access modifiers such as private, public and global.
Q294. What is an Apex trigger in Salesforce?
Triggers are programmatic event handlers that are executed when a DML operation occurs on an sObject record. They run before or after insert, update, delete, upsert and undelete, and give access to context variables such as Trigger.new, Trigger.old, Trigger.newMap and Trigger.oldMap.
Q295. Can a Set store duplicate values?
No. A Set stores only unique values. A List, on the other hand, can contain duplicate values.
Q296. How do you get the currently logged-in user's ID in Apex?
Use UserInfo.getUserId() to get the current logged-in user's ID in Apex.
Q297. How do you convert a CSV file uploaded through a Visualforce page into a string?
Use the toString() method to convert the Blob to a string.
String csvAsString = csvFileContents.toString();
Q298. How do we bulkify a trigger?
Bulkification requires iterating over all the records in the trigger context instead of assuming a single record, and keeping SOQL/DML outside the loop.
for (Account ac : Trigger.new) {
// your logic here
}
Q299. How can we get the old value of a field in a trigger?
Use Trigger.oldMap (or Trigger.old) to get the previous values of the fields.
Q300. Can we modify records directly in Trigger.new?
Trigger.new is a read-only list (you cannot add or remove records from it), but the field values of its records can be changed in a before trigger.
Q301. What does the error "List has no rows for assignment to SObject" mean?
It means the query/list you are trying to assign to a single sObject returned no rows, i.e. the list you are trying to access has no values in it.
Q302. Why should we not write a SELECT query inside a for loop?
Writing a SOQL query inside a for loop may hit the governor limit of 100 SOQL queries per transaction.
Q303. How can you show a custom error message in a trigger?
This can be done using the addError() method on a record or a field in the trigger.
Q304. How do you convert a Blob variable into a String?
Use the toString() method to convert the Blob into a String.
Q305. Can you write SOSL in a trigger?
Earlier this was not allowed, but SOSL queries are now allowed in triggers.
Q306. What are the access modifiers in Apex?
Access modifiers define the scope of members (variables and methods):
private - members can be accessed only within the class. This is the default if no modifier is specified.
protected - members can be accessed within the class and in the child (extending) classes; used with inheritance.
public - members can be accessed anywhere in the same namespace/application.
global - members are visible to all Apex everywhere, including other namespaces; this is what you use for web services and integrations with third-party (external) applications.
Related points:
Any method exposed as a web service (webservice keyword) or in a managed package API must be global.
Static members get memory once during execution and are called by the class name. A static method cannot use non-static variables, but a non-static method can use both static and non-static variables.
Q307. How can you lock records in Apex?
Use FOR UPDATE in the query to lock the records.
List<Contact> cons = [SELECT Id, Name FROM Contact LIMIT 10 FOR UPDATE];
Q308. Is there any limit on how many elements can be stored in an Apex collection (list, set, map)?
There is no such limit on the number of elements, but you need to consider the heap size limit (6 MB for synchronous transactions as of now).
Q309. How can you access a custom label in Apex?
Use the System.Label namespace.
String custLabelStr = System.Label.LabelNameHere;
Q310. How can you get all the keys of a Map variable?
Use the keySet() method.
Set<Id> idSet = mapName.keySet();
Q311. How can you convert text to uppercase in Apex?
stringName.toUpperCase();
Q312. How can you convert an Integer into a String in Apex?
String.valueOf(integerName);
Q313. Can you perform a DML operation inside a constructor?
Technically yes - Apex allows DML statements inside a constructor, and it counts against the same governor limits as any other DML.
However it is bad practice: a constructor should only initialize state. Putting DML there makes the class hard to test, causes unexpected records to be created every time the object is instantiated, and can break bulk processing.
There is one hard restriction: a Visualforce controller constructor cannot perform DML (or a callout) - the platform throws an error because a page is only being rendered, not submitted. Move the DML into an action method that is called from a command button.
The same rule applies to a constructor that runs during a page's getter evaluation and to any code that runs before the first save point.
Q314. How can you hard delete records in Apex?
Delete the records and then empty the recycle bin.
delete myAccList;
Database.emptyRecycleBin(myAccList);
Q315. What data types can a Set store?
A Set can store all primitive data types and sObjects, but not collections.
Q316. When a lead is converted into an account/contact, will the trigger on Account/Contact fire?
Yes, insert triggers on Account, Contact and Opportunity fire during lead conversion. In Setup you can additionally enable or disable whether validation rules and triggers apply for converted leads.
Q317. What is an sObject type?
An sObject refers to any object that can be stored in the Force.com platform database.
sObject s = new Contact();
Q318. What is the significance of the static keyword?
Methods and variables defined as static are initialised only once, when the class is loaded, and belong to the class rather than to an instance. Static variables are also not transmitted as part of the view state of a Visualforce page.
Q319. What are the different exceptions in Apex?
Apex exceptions can be built-in or custom. The Exception class is the superclass of all the built-in exceptions. To create a custom exception, the class name should end with the string 'Exception' and it must extend Exception (or another built-in or custom exception class).
Q320. What access modifiers can be used for class members (methods and variables)?
Class members can have any of these four access modifiers:
global
public
protected
private
Q321. What does heap mean in Apex?
Every Apex transaction has its own heap - the memory used to hold the objects created during the transaction. It is garbage collected at the end of the transaction, and its size is capped by the heap size governor limit.
Q322. What are the differences between a List and a Set?
A Set stores only unique elements, while a List can store duplicate elements.
Elements stored in a List are ordered (indexed), while those in a Set are unordered.
Q323. What is the total heap size limit for synchronous and asynchronous transactions?
Synchronous: 6 MB
Asynchronous: 12 MB
Q324. Can a Map key hold a null value?
Yes, a Map key can be null.
Q325. What happens when you add an entry with a key that already exists in the Map?
The existing value for that key is overwritten with the new value.
Q326. Can you have two different keys of type String that differ only in case?
Yes, this is possible. String keys in a Map are case-sensitive, so keys differing only in case are treated as distinct.
Q327. What is the order of execution when a record is saved in Salesforce?
Asked at: Cognizant
1. The record is loaded from the database (for an update) or initialised from the submitted values (for an insert).
2. New field values from the request overwrite the old values.
3. System validation rules run (required fields, field formats, maximum lengths), and for a new record the layout-specific rules run.
4. before triggers execute.
5. Custom validation rules, duplicate rules and system validation run again.
6. The record is saved to the database, but not yet committed.
7. after triggers execute.
8. Assignment rules run.
9. Auto-response rules run.
10. Workflow rules run; if a field update fires, the record is updated again and before/after update triggers fire one more time (only once).
11. Escalation rules run.
12. Processes (Process Builder), flows launched by processes, and record-triggered flows configured to run after the record is saved execute.
13. Entitlement rules run.
14. Roll-up summary fields on the parent are recalculated, and the parent record goes through its own save process; grandparent roll-ups follow.
15. Criteria-based sharing rules are recalculated.
16. All DML operations are committed to the database.
17. Post-commit logic executes - sending email, enqueued asynchronous Apex (future methods, queueable jobs), and so on.
Note that the exact order can change between releases, so always confirm against the current documentation.
Q328. What is the difference between a before trigger and an after trigger?
Before trigger - fires before the record is saved to the database. The records in Trigger.new are editable, so you can assign values directly (no additional DML is required, and no insert/update statement should be issued on them). Used for validation and for defaulting/updating fields on the same record.
After trigger - fires after the record has been saved (but before commit). The records are read only, so you cannot modify Trigger.new directly. Ids and system fields such as Id, CreatedDate and LastModifiedDate are available, so this is where you create or update related records, send emails or fire asynchronous work.
Q329. What are the Apex coding best practices you follow?
Bulkify your code - always work on collections (List, Set, Map<Id, SObject>) so that the logic works for 1 record or 200 records.
Never put SOQL queries or DML statements inside for loops; query once into a map and DML once outside the loop.
Bulkify the helper methods as well, not just the trigger.
Use collections, streamlined queries and efficient for loops (for (Account a : [SELECT ... ])).
Streamline multiple triggers on the same object - keep one trigger per object and delegate the logic to a handler/helper class.
Be careful when querying large data sets; use selective filters, LIMIT and batch Apex where needed.
Use the Limits Apex methods (for example Limits.getQueries(), Limits.getDMLRows()) to avoid hitting governor limits.
Use @future/queueable appropriately, and never call a future method from another future method.
Write test methods that verify large data sets (200 records) and both positive and negative paths.
Avoid hardcoding Ids anywhere - use custom settings, custom metadata or queries by developer name.
Prevent recursion (a static Boolean flag or a custom setting), otherwise you get CPU time-out errors.
Use Trigger.new, Trigger.old, Trigger.newMap.get() and Trigger.oldMap.get() rather than re-querying the same records.
Use the safe navigation operator ?. instead of long sequential null checks, for example a[x]?.aMethod().aField evaluates to null if a[x] is null.
Keep reusable code in helper methods and keep messages in a constants class of static variables.
Q330. What are the main Apex governor limits you should remember?
Per synchronous transaction:
Number of SOQL queries: 100 (200 in asynchronous Apex).
Number of records retrieved by SOQL: 50,000.
Number of SOSL queries: 20 (the notes list 2,000 records returned per SOSL query).
Number of DML statements: 150.
Number of records processed by DML: 10,000.
Maximum CPU time: 10 seconds synchronous / 60 seconds asynchronous.
Maximum heap size: 6 MB synchronous / 12 MB asynchronous.
Number of callouts: 100 per transaction.
Number of @future calls: 50 per transaction.
Number of queueable jobs added to the queue: 50.
Number of email invocations: 10.
Number of Apex mobile push calls: 10.
Some configuration limits:
Active validation rules per object: 100.
Custom fields per object: 500; custom objects: 400; custom apps: 10; tabs: 100.
Custom report types: 400; dynamic dashboards per org: 3; active flows: 500.
Mass email: 5,000 external addresses per day per org (GMT based).
Q331. What is the difference between DML statements (insert) and the Database class methods (Database.insert)?
The Database class provides static methods that allow partial processing of records; they are called on the class name, for example Database.insert().
Database.insert(), Database.update(), Database.upsert(), Database.delete(), Database.merge(), Database.undelete().
All of them accept the records plus an allOrNone parameter: Database.insert(recordList, true|false).
allOrNone = true (the default) - either all records are saved or none of them are, exactly like a plain DML statement.
allOrNone = false - partial processing; the good records are saved and the failures are returned in the result rather than throwing an exception.
Plain DML statements (insert, update, delete, upsert, merge, undelete) are all-or-nothing and throw a DmlException on any failure.
Return types of the Database methods
Database.insert() - Database.SaveResult
Database.update() - Database.SaveResult
Database.upsert() - Database.UpsertResult
Database.merge() - Database.MergeResult
Database.delete() - Database.DeleteResult
Database.undelete() - Database.UndeleteResult
merge merges a record into a parent record and is supported only on Lead, Contact and Account - it does not work on custom objects.
Q332. What is the difference between a virtual class and an abstract class in Apex?
A virtual class can be instantiated directly, whereas an abstract class cannot be instantiated.
Only abstract classes can contain abstract methods (methods with no body that the child class must implement).
Virtual methods can exist in both virtual and abstract classes; normal (non-virtual) methods cannot be overridden.
In the child class you must use the override keyword to provide the implementation of a parent's virtual or abstract method.
An abstract class gives you 0-100% abstraction, whereas an interface gives 100% abstraction: interface methods have no body and all methods implemented from an interface must be declared public in the implementing class.
Q333. When do you use the @InvocableMethod annotation and what are its rules?
@InvocableMethod is used when an Apex method has to be invoked from Process Builder (or from a Flow or the REST API) rather than from Apex code.
The method must be public or global and static.
Only one method in a class can carry the @InvocableMethod annotation.
The method can accept only one parameter, and it must be a list (a list of primitives, sObjects or a list of a custom invocable-variable class).
Triggers cannot call an @InvocableMethod.
public class ProcessApexWork {
@InvocableMethod
public static void processLead(List<Id> ids) {
List<Lead> leads = [SELECT Id FROM Lead WHERE Id IN :ids];
for (Lead l : leads) {
l.LastName = 'TestLead';
}
upsert leads;
}
}
Q334. How do you compare old and new field values in an update trigger using Trigger.oldMap?
Look up the matching old version of each record by Id in Trigger.oldMap, then compare it with the record in Trigger.new.
trigger Winning on Opportunity (before update) {
for (Opportunity opp : Trigger.new) {
// Access the "old" record by its ID in Trigger.oldMap
Opportunity oldOpp = Trigger.oldMap.get(opp.Id);
// Trigger.new records are conveniently the "new" versions!
Boolean oldOppIsWon = oldOpp.StageName.equals('Closed Won');
Boolean newOppIsWon = opp.StageName.equals('Closed Won');
// Check that the field was changed to the correct value
if (!oldOppIsWon && newOppIsWon) {
opp.I_am_Awesome__c = true;
}
}
}
Trigger.old can also be used directly as a list, for example to re-query the old records:
List<Account> accts = [SELECT Id, FieldUpdatedByWorkflow__c FROM Account WHERE Id IN :Trigger.old];
Q335. Why does Trigger.newMap throw a null pointer exception in a before insert trigger?
Because record Ids are not assigned until the record is saved. In a before insert context the records in Trigger.new have no Id yet, so Trigger.newMap is null (and Trigger.oldMap/Trigger.old are null for inserts altogether).
trigger BeforeInsertTrigger on Account (before insert) {
Set<Id> sid = new Set<Id>();
for (Account a : Trigger.new) {
sid.add(a.Id);
System.debug('sid :' + sid);
// This line raises a Null Pointer Exception because Trigger.newMap
// doesn't work in a before insert trigger.
// In an after insert trigger, Trigger.newMap returns the Account values.
Account acc = Trigger.newMap.get(a.Id);
System.debug('Acc :' + acc);
}
}
Use after insert if you need Trigger.newMap or the record Ids.
Q336. How do you safely add an item to a multi-level nested Map in Apex?
Build each level only if it is missing, then add to the innermost collection. The pattern below stores a Case in a map keyed at three levels.
Map<String, Map<String, Map<String, Case[]>>> xyzMap = new Map<String, Map<String, Map<String, Case[]>>>();
addItemToMap(xyzMap, 'firstkey', 'secondkey', 'thirdkey', new Case(Subject = 'Test'));
private static void addItemToMap(Map<String, Map<String, Map<String, Case[]>>> nestedMap,
String firstKey, String secondKey, String thirdKey, Case c) {
Map<String, Map<String, Case[]>> firstLevel = nestedMap.get(firstKey);
if (firstLevel == null) {
firstLevel = new Map<String, Map<String, Case[]>>{};
nestedMap.put(firstKey, firstLevel);
}
Map<String, Case[]> caseMap = firstLevel.get(secondKey);
if (caseMap == null) {
caseMap = new Map<String, Case[]>{};
firstLevel.put(secondKey, caseMap);
}
Case[] cList = caseMap.get(thirdKey);
if (cList == null) {
cList = new Case[]{};
caseMap.put(thirdKey, cList);
}
cList.add(c);
}
Because maps and lists are passed by reference, mutating firstLevel, caseMap or cList updates the structure held in nestedMap.
Q337. What do Schema.getGlobalDescribe(), Schema.DescribeFieldResult and Schema.PicklistEntry give you?
These are the dynamic Apex (describe) methods used to inspect metadata at runtime.
Schema.getGlobalDescribe() - returns a map of all sObject names (keys) to sObject tokens (values) for the standard and custom objects defined in your organization.
Schema.getGlobalDescribe().get('Task') - returns the token for one specific object, from which you can call getDescribe() for its details.
Schema.DescribeFieldResult - describes one field: label, type, length, whether it is accessible/createable/updateable.
Schema.PicklistEntry - each entry of a picklist field, used to read picklist values (including dependent picklist values through the validFor bitmap).
Field dependencies for an object such as Task are configured under Object > Activity Custom Fields (picklist) > Field Dependencies.
SOQL / SOSL & Data Model
45 questions
Q338. What is an object relationship in Salesforce, and what relationship types are available?
There are three main relationship types in Salesforce:
Lookup relationship - links two objects together. loosely coupled child-parent.
Master-detail relationship - also links two objects, but creates a tight relationship between parent and child. The child record inherits the security of the parent, and if the parent is deleted all associated child records are also deleted. roll-up summary fields, which let you calculate data on the parent from the children.
Many-to-many relationship (junction object) - lets you model a many-to-many relationship between two objects. It is created with an object that has two master-detail relationships to two parent objects.
Q340. Explain the use of a roll-up summary field and where it can be used.
calculate data on the parent from the children.
only be used on the master side of a master-detail relationship
The available aggregate types are COUNT, SUM, MIN and MAX.
Limit: 25 roll-up summary fields per object.
Q341. What is the difference between WhoId and WhatId in activities?
WhoId refers to people - a Contact or Lead Id. WhatId refers to objects/records Id.
Q342. What is a junction object in Salesforce, and how does it create a many-to-many relationship?
A junction object is an object used to create a many-to-many relationship between two other objects.
If an object has two master-detail relationship fields, that object is known as a junction object.
Conceptually it is the same as having two tables with primary keys and a third table that holds both primary keys as foreign keys.
Q343. What is cascade deletion in Salesforce?
Cascade deletion refers to the automatic deletion of related child records when a parent record is deleted. In a master-detail relationship, deleting the parent always deletes the children. In a lookup relationship, cascade delete is not the default, but the field can be configured so that deleting the parent deletes the child (or so that deletion is blocked while children exist). Cascade deletes bypass validation rules, triggers can still fire, and the records go to the Recycle Bin.
Q344. What is a lookup relationship?
It is used to create a relation with another object to get the values from that object.
The lookup field is an optional field by default.
Lookup fields are created on the child object.
Governor limit: 40 lookups per object.
It gives two options when the parent record is deleted: (a) clear the value from the child, or (b) don't allow the deletion if a record is associated with a child.
It is a one-to-many relationship, and the child does not inherit the parent's security or ownership.
Also noted:
Up to 25 allowed per object.
Parent is not a required field.
No impact on security and access.
No impact on deletion.
Can be multiple layers deep.
Lookup field is not required.
Q345. What is a master-detail relationship?
A master-detail relationship is used to get values from another object.
The master-detail field is a mandatory (required) field on the detail record.
Master-detail fields are also created on the child object.
Governor limit: 2 master-detail relationships per object.
If a parent record is deleted, all the corresponding child records are also deleted.
Roll-up summary fields can only be used with master-detail relationships.
Two master-detail relationships on one object create the junction object used for a many-to-many relationship.
The detail record inherits the ownership and sharing of the master record.
Q347. What is a data model?
Answer supplied - source left blank.
the objects, fields, and relationships known as data model that represent the records.
Q348. How do you count records in SOQL when there are 50 million records?
Use an aggregate count query with a WHERE clause, which is executed on the server and is not subject to the 50,000-row retrieval limit:
SELECT COUNT() FROM ObjectName WHERE YourConditions
Q349. What is the difference between an External ID and a Unique ID?
Asked at: Accenture
Answer supplied - source left blank.
Unique is a datatype in objects where no other record can contains same value.
External ID is treated as a primary key in external system in salesforce treated as a Foreign Key.
Q350. Write a SOQL query to find the unique designations of employees.
Asked at: Accenture
List<AggregateResult> results = [SELECT Designation__c, COUNT(Id) total
FROM Employee__c
GROUP BY Designation__c];
Q351. How do you find duplicate values using an index?
Asked at: Cloud 360
Use the GROUP BY clause in SOQL together with HAVING COUNT(Id) > 1, which returns only the values that occur more than once:
SELECT Name, COUNT(Id)
FROM Account
GROUP BY Name
HAVING COUNT(Id) > 1
Indexed/External ID fields make this efficient. In Apex the same is achieved by adding values to a Set and detecting the ones already present.
Q352. What are the types of SOQL statements in Salesforce?
Salesforce Object Query Language is used to query records from the Database.com-based database according to the requirement. There are 2 types of SOQL statements:
Static SOQL
Dynamic SOQL
1. Static SOQL: The static SOQL statement is written in [] (square brackets). These statements are similar to LINQ (Language Integrated Query).
String searchFor = 'Jones';
Contact[] contacts = [SELECT testfield__c, FirstName, LastName FROM Contact WHERE LastName = :searchFor];
2. Dynamic SOQL:
It refers to the creation of a SOQL string at run time with Apex code.
Dynamic SOQL enables you to create more flexible applications.
To create a dynamic SOQL query at run time, use the Database.query() method in one of the following ways:
Return a single sObject when the query returns a single record: sObject s = Database.query(String_limit_1);
Return a list of sObjects when the query returns more than a single record.
Examples:
// Example 1
String myTestString = 'TestName';
List<MyCustomObject__c> L = Database.query('SELECT Id FROM MyCustomObject__c WHERE Name = :myTestString');
// Example 2
String resolvedField_L = myVariable.field__c;
List<myCustomObject__c> L = Database.query('SELECT Id FROM myCustomObject__c WHERE field__c = ' + resolvedField_L);
Q353. What is the syntax of a SOQL statement?
SELECT field1, field2, .... FROM Object_Type [WHERE condition]
Examples:
List<Account> accountList = [SELECT Id, Name FROM Account];
List<Account> accountList = [SELECT Id, Name FROM Account WHERE AnnualRevenue < 10000];
Q354. What is GROUP BY in SOQL?
With API version 18.0 and later, you can use GROUP BY with aggregate functions such as SUM() or MAX() to summarize the data and enable you to roll up query results rather than having to process the individual records in your code.
Syntax:
[GROUP BY field GROUP BY LIST]
Q355. What are SOSL statements in Salesforce Apex?
A SOSL statement evaluates to a list of sObjects, where each list contains the search results for a particular sObject type. The result lists are always returned in the same order as they were specified in the query.
If a SOSL query does not return any records for a specified sObject type, the search results include an empty list for that sObject.
For example, you can return a list of accounts, contacts, opportunities and leads that begin with the phrase "map":
List<List<sObject>> searchList = [FIND 'map*' IN ALL FIELDS RETURNING Account(Id, Name), Contact, Opportunity, Lead];
Note: The syntax of the FIND clause in Apex differs from the syntax of the FIND clause in the SOAP API.
In Apex, the value of the FIND clause is demarcated with single quotes:
FIND 'map*' IN ALL FIELDS RETURNING Account(Id, Name), Contact, Opportunity, Lead
In the Force.com API, the value of the FIND clause is demarcated with braces:
FIND {map*} IN ALL FIELDS RETURNING Account(Id, Name), Contact, Opportunity, Lead
From searchList you can create arrays for each object returned:
Account[] accounts = ((List<Account>)searchList[0]);
Contact[] contacts = ((List<Contact>)searchList[1]);
Opportunity[] opportunities = ((List<Opportunity>)searchList[2]);
Lead[] leads = ((List<Lead>)searchList[3]);
Q356. What is a self relationship?
A self relationship is a lookup relationship to the same object. For example, take an object "Merchandise". Here we can create a relationship between Account and Account (the same object). That is called a self relationship.
Q359. How do you query a query in SOQL (nested SOQL queries)?
Use nested SOQL queries. Here's an example of querying a parent and two child objects in one query, using the relationship name for each related list of objects:
List<Account> accsWithChildren = [
SELECT Id, Name, CreatedDate,
(SELECT Id, CreatedDate FROM Tasks ORDER BY CreatedDate DESC LIMIT 1),
(SELECT Id, Service_Date__c FROM Custom_Object__r ORDER BY Service_Date__c DESC LIMIT 1)
FROM Account WHERE Id IN :setOfIds];
You can then loop through those Accounts in Apex, and for each one there is a list (size 0 or 1) of Tasks and Custom_Object__c:
for (Account a : accsWithChildren) {
List<Task> theseTasks = a.Tasks;
List<Custom_Object__c> otherObjects = a.Custom_Object__r;
// do something with these records
}
Q360. How can I create a many-to-many relationship?
Lookup and master-detail relationships are one-to-many relationships. We can create a many-to-many relationship by using a junction object. A junction object is a custom object with two master-detail relationships.
Q361. How do you create a roll-up summary field on a lookup relationship?
Not possible. Roll-up summary is enabled only for master-detail relationships.
Q362. How can you sort the results of a SOQL query?
Use the ORDER BY clause in the SELECT query to sort the list of returned records.
Q363. What happens to the detail record when the master record is deleted?
The detail record is also deleted (master-detail relationships cascade the delete).
Q364. What happens to the child record when the parent record is deleted in a lookup relationship?
The child record is not deleted; it remains, with the lookup field cleared.
Q365. How many records can a SOQL query return?
As of now, the limit is 50,000 records returned by SOQL queries in a single transaction.
Q366. How many records can a SOSL query return?
It can return up to 2,000 records as per the current governor limit.
Q367. How do you fire a dynamic query in SOQL?
Use Database.query().
List<Account> accList = Database.query('SELECT Name FROM Account');
Q368. Can you have roll-up summary fields in the case of a parent-child (lookup) relationship?
No. Roll-up summary fields are available only in the case of a master-detail relationship.
Q369. What is SOSL?
SOSL (Salesforce Object Search Language) is a search query language that can return records from multiple objects at once, as a list of lists.
Q370. Can you change the master of a detail record in Salesforce?
Yes, provided the "Allow reparenting" option has been ticked in the master-detail field settings. Otherwise the field is read-only after creation and the master cannot be changed.
Q371. How can you create a relationship between two objects in Salesforce?
A relationship can be set up by creating either a lookup relationship field or a master-detail relationship field on the object.
Q372. Can you create a roll-up summary field on the parent object?
Yes, but only if the relationship between the objects is of master-detail type. Roll-up summary fields are created on the master (parent) object and summarise detail (child) records.
Q373. What is the use of the OFFSET keyword in a SOQL query?
OFFSET returns records starting from the desired position in the result list. For example, if you specify OFFSET 8, all records from position 9 onwards are returned.
Q374. What happens to contacts when an account is deleted?
When an account is deleted, all the contacts under it are also deleted (they go to the recycle bin along with the account).
Q375. Expand SOQL and SOSL.
SOQL - Salesforce Object Query Language
SOSL - Salesforce Object Search Language
Q376. How can you query all records, including deleted ones, using a SOQL statement?
Use the ALL ROWS keyword. This queries all records, including deleted records in the recycle bin and archived activities.
Q377. Which field data types can be used as external IDs?
An external ID field can be of type Text, Number or Email (and Auto Number).
Q378. What return types can a SOQL query return?
A SOQL query can return a list of sObjects, a single sObject, or an Integer (when using COUNT()).
Q379. Can a standard object appear as the detail object in a master-detail relationship?
No, you cannot have a standard object as the detail object in a master-detail relationship. A standard object can only be the master.
Q380. What is the difference between a Lookup relationship and a Master-Detail relationship?
refer shortcut Notes.
Q381. What must be true before you can convert a Lookup relationship to a Master-Detail relationship, and vice versa?
Lookup to Master-Detail: every child record must be associated with a parent record. Check the lookup field on the child object for every record - it must not be empty.
Master-Detail to Lookup: there must not be any roll-up summary field on the parent object.
Q382. How do you write parent-to-child and child-to-parent relationship queries in SOQL?
Child to parent (dot notation)
-- standard objects: use the parent object name
SELECT Name, Email, Account.Type, Account.Industry FROM Contact
-- custom objects: replace c with r on the relationship name
SELECT Name, Position__r.Name, Position__r.Salary__c, Position__r.Status__c
FROM Candidate__c
Parent to child (subquery)
-- standard objects: use the plural child relationship name
SELECT Id, Name, (SELECT Id, Name FROM Contacts) FROM Account
SELECT Id, Name, (SELECT Id, Name FROM Contacts), (SELECT Id, Name FROM Opportunities) FROM Account
-- custom objects: the child relationship name ends in __r
SELECT Name, (SELECT Id, Name FROM Candidates__r) FROM Position__c
Limits
20 parent-to-child relationships per query, and only one level of parent-to-child nesting.
35 child-to-parent relationships per query, and no more than 5 levels of child-to-parent traversal, for example Contact.Account.Owner.FirstName.
Joins do not really exist in SOQL - relationships do. For a join-like result use a semi-join: SELECT Favorite_Wine__c, (SELECT FirstName__c FROM Children__r) FROM Adult__c WHERE Id IN (SELECT Adult_Lookup_Field__c FROM Child__c).
Bind variables are prefixed with a colon: WHERE AccountId = :ac.Id for a single value and WHERE AccountId IN :accIds for a collection.
A query built as a string is run with Database.query(s) (dynamic SOQL).
LWC
40 questions
Q383. What is Lightning Message Service?
Lightning Message Service (LMS) allows communication between Visualforce pages and Lightning components (both Aura and LWC) anywhere on a Lightning page. The LMS API lets you publish a message across the Lightning Experience DOM and subscribe to the same message anywhere on the page. It uses a Lightning Message Channel (a .messageChannel-meta.xml metadata file), and in LWC you use publish, subscribe, unsubscribe and MessageContext from the lightning/messageService module.
Q384. What is lazy loading in LWC, and how do you implement it?
Lazy loading is an optimization technique that loads content on demand. Instead of loading all the data and rendering it in one go (bulk loading), lazy loading loads only the section that is currently required and delays the rest until the user needs it.
In LWC it is commonly implemented by:
Loading data page by page from Apex with OFFSET/LIMIT or a cursor, triggered by lightning-datatable's onloadmore (infinite loading) event.
Using renderedCallback or an IntersectionObserver to fetch the next chunk when the user scrolls to the bottom.
Dynamically importing a component (import('c/myComponent')) or using lazy component creation so heavy components render only when needed.
Loading static resources with loadScript / loadStyle only at the moment they are used.
Q385. What are design attributes in Lightning Web Components?
Design attributes expose a component's public properties so that a System Administrator can configure them in the Lightning App Builder, Experience Builder or Flow Builder. You declare the property with @api in the JavaScript file, and then expose it in the .js-meta.xml file inside a targetConfig using a <property> tag, where you set the name, type, label, description, default and (optionally) a datasource of allowed values.
<targetConfigs>
<targetConfig targets="lightning__RecordPage">
<property name="title" type="String" label="Card Title" default="Details"/>
</targetConfig>
</targetConfigs>
Q386. What is the use of the .js-meta.xml file in a Lightning Web Component?
The .js-meta.xml configuration file defines the component's metadata:
isExposed - true or false, controlling whether the component is visible and usable in tools such as the Lightning App Builder and Experience Builder.
apiVersion - the API version of the component.
targets - where the component can be dropped (lightning__RecordPage, lightning__AppPage, lightning__HomePage, lightning__Tab, lightning__FlowScreen, etc.).
targetConfigs - per-target configuration, including design properties (public @api properties exposed to admins), supported objects and required permissions.
masterLabel and description shown in the builders.
Q387. Can we write tests for LWC components?
Yes. LWC unit tests are written with Jest (via sfdx-lwc-jest). The test files are placed in a sub-folder of the component called tests, and follow the naming convention <component>.test.js. Jest tests render the component in a virtual DOM, assert on the rendered output and mock Apex and wire adapters. They are run with npm run test:unit and do not count towards Apex code coverage.
Q388. Can we use the same component name for an LWC and an Aura component?
No. LWC and Aura components share the same namespace, so you cannot have an Aura component and a Lightning web component with the same name in the same namespace.
Q389. How do you select a specific tag value in the DOM in LWC?
Use this.template.querySelector() (or querySelectorAll()) to query the component's own shadow DOM:
this.template.querySelector('div'); // <div>First</div>
Note that querySelector returns the first matching element, that it cannot cross the shadow boundary into a child component's template, and that DOM queries should only be run in renderedCallback or later, once the DOM exists. Prefer data-* attributes or lwc:ref over CSS classes for selection.
Q390. What is the ES6 export function, and how do you share JavaScript code between LWC components?
You share JavaScript code across components using ES6 modules and the export keyword on variables and functions, placed in a service (utility) component, and then import them where needed.
// c/mortgage - mortgage.js
const showMessage = (message) => {
alert('this is an alert message ' + message);
};
export { showMessage, getTermOptions, calculateMonthlyPayment };
// consuming component
import { getTermOptions, calculateMonthlyPayment } from 'c/mortgage';
The service component's folder needs no HTML template - only the JavaScript file and its meta file.
Q391. How do you import static resources in LWC?
import myResource from '@salesforce/resourceUrl/resourceReference';
For a zipped resource you append the path inside it, for example myResource + '/images/logo.png'. Scripts and stylesheets from a static resource are loaded with loadScript and loadStyle from lightning/platformResourceLoader.
Q392. How do you import custom labels in LWC?
import labelName from '@salesforce/label/labelReference';
For example import greeting from '@salesforce/label/c.Greeting';. Expose it to the template by assigning it to a property, typically grouped in a label object.
Q393. How do you get the current user Id in LWC?
Import the user property from the @salesforce/user scoped module:
import Id from '@salesforce/user/Id';
import isGuest from '@salesforce/user/isGuest';
The general form is import property from '@salesforce/user/property';. For more user fields, use the getRecord wire adapter with the user Id.
Q394. How do you get the form factor value in LWC?
import FORM_FACTOR from '@salesforce/client/formFactor';
The general form is import formFactorPropertyName from '@salesforce/client/formFactor';. The value is Large (desktop), Medium (tablet) or Small (phone).
Q395. What is a custom event in LWC, and how do you create one?
A custom event is how a child component communicates upward to its parent. You create it with the CustomEvent constructor and dispatch it:
this.dispatchEvent(
new CustomEvent(name, {
bubbles: true/false,
composed: true/false,
cancelable: true/false,
detail: { /* payload */ }
})
);
The event name must be lowercase with no spaces, the parent listens with on<eventname> in the template, and the payload is read from event.detail.
Q396. How do you navigate from an LWC to a Visualforce page?
Use the NavigationMixin from lightning/navigation with a standard__webPage page reference pointing at the Visualforce URL:
import { NavigationMixin } from 'lightning/navigation';
export default class Nav extends NavigationMixin(LightningElement) {
goToVf() {
this[NavigationMixin.Navigate]({
type: 'standard__webPage',
attributes: {
url: '/apex/MyVfPage?id=' + this.recordId
}
});
}
}
Q397. What is the field spanning limit in LWC?
When referencing relationship (spanning) fields - for example with getRecord and imported field references - you can refer to relationship fields up to 5 levels deep.
Q398. How do you pass a list of sObject records from an LWC to a flow?
Define the list variable in the component's JavaScript with @api so it is exposed as a public property to the flow. The meta file configuration remains the same, and the property type is declared as @salesforce/schema/<SobjectApiName>[] in the targetConfig for lightning__FlowScreen:
<targetConfig targets="lightning__FlowScreen">
<property name="contacts" label="Contacts"
type="@salesforce/schema/Contact[]" role="outputOnly"/>
</targetConfig>
The flow can then consume the collection as an output variable of the screen component.
Q399. Name a few LWC targetConfigs (targets).
lightning__AppPage
lightning__HomePage
lightning__RecordPage
lightning__Tab
lightning__FlowScreen
Others include lightningCommunity__Page, lightningCommunity__Default, lightning__UtilityBar and lightning__RecordAction.
Q400. LWC follows which framework?
Lightning Web Components are built on the Salesforce Lightning Platform, using modern web standards (Web Components, ES6 modules, custom elements) with a thin Salesforce layer on top.
Q401. What is a Lightning web component bundle?
An LWC bundle contains an HTML file, a JavaScript file, and a metadata configuration file (.js-meta.xml); these files are created once you create a Lightning web component.
You can also create a .css file for styling.
You can also create an SVG file for the purpose of displaying an icon.
The HTML and JavaScript files are mandatory, and all files in the bundle must share the folder's name.
Q402. What is @AuraEnabled(cacheable=true)?
If you want to access the data, then we should include this annotation on an Apex class method.
Q403. What is @wire?
If you are dealing with Apex class methods, then we should use the wire property.
Q404. How many files are generated when you create an LWC component?
Three files are generated:
.html file
JavaScript file (.js)
Metadata file (.xml)
Q405. How do you call an Apex class method from a Lightning web component's JavaScript file?
There are two ways:
@wire
Imperative method
.then(result=>{
this.records=result;
this.error=undefined;
})
.catch(error=>{
this.error=error;
this.records=undefined;
});
Q406. How do you refresh the page in LWC?
import { refreshApex } from '@salesforce/apex';
Q407. What is the difference between Aura Lightning components and Lightning Web Components?
Aura components
Built on Salesforce's proprietary Aura framework, introduced in 2014-15 (originally for Salesforce1 mobile development).
A component is a bundle of up to 8 files: Component (.cmp), Controller, Helper, Style, Documentation, Renderer, Design and SVG.
Markup uses Aura/Lightning tags with a colon, for example <lightning:input>, <aura:iteration>, <aura:if>.
Attributes are declared with <aura:attribute>; expressions are {!v.myValue} where v is the view and c is the controller.
Communication between components uses component events and application events, plus aura:method for parent-to-child calls.
Apex is called through @AuraEnabled methods with component.get("c.method"), action.setParams() and $A.enqueueAction(action).
Lightning Web Components (LWC)
Built on modern web standards - custom elements, Shadow DOM, HTML templates, ES6+ modules - so most of the framework is native to the browser; it is lightweight, open source and gives better performance.
A component is a folder with <component>.html, <component>.js, <component>.js-meta.xml, and optionally .css, .svg and a tests folder.
Markup uses hyphenated tags, for example <lightning-input>, and the custom namespace prefix c-, for example <c-contact-tile>.
The JavaScript file is an ES6 module: import { LightningElement, api, track, wire } from 'lwc'; and export default class MyComponent extends LightningElement { }.
Data binding is direct: {propertyName} in the template, no v.; conditional rendering uses <template if:true={flag}> and lists use <template for:each={items} for:item="item"> or iterator:it.
Public properties are exposed with @api, reactivity is built in (before Spring '20 you needed @track), and events are standard DOM CustomEvents.
Lifecycle hooks are constructor(), connectedCallback(), renderedCallback(), disconnectedCallback() and errorCallback().
Aura components and Lightning web components can coexist and interoperate on the same page: an Aura component can contain an LWC, but an LWC cannot contain an Aura component.
Q408. What are the LWC lifecycle hooks, and in what order do they fire?
LWC exposes five lifecycle hooks on the component class.
constructor() - fires when a component instance is created. The first statement must be super() with no parameters. Don't use document.write() or document.open() here, and don't touch this.template (the element isn't in the DOM yet).
connectedCallback() - fires every time the component is inserted into the DOM.
renderedCallback() - unique to Lightning Web Components. Use it to run logic after the component has finished the rendering phase. It can fire many times, so guard one-time logic with a boolean such as hasRendered.
disconnectedCallback() - fires when the component is removed from the DOM. Use it to clean up (for example, release a message context or remove listeners).
errorCallback(error, stack) - captures errors thrown in the component's descendants (an error boundary).
export default class LifeCycleHooks extends LightningElement {
constructor() {
super();
alert('I am in Constructor');
}
connectedCallback() {
alert('I am in Connected callback');
}
disconnectedCallback() {
alert('I am in DisConnected callback');
}
renderedCallback() {
alert('I am in Rendered callback');
}
errorCallback(error, stack) {
alert('I am in Error callback');
}
}
Q409. What do the bubbles and composed properties do when an LWC fires a custom event?
They control event propagation once the event is fired.
bubbles - a Boolean indicating whether the event bubbles up through the DOM. Defaults to false.
composed - a Boolean indicating whether the event can cross the shadow boundary. Defaults to false.
Propagation has two phases:
Capture phase (rarely used) - the event moves down the DOM tree, from the top to the element that fired the event.
Bubble phase (widely used) - the event moves back up the DOM tree, retracing its steps.
In LWC you create events with the standard CustomEvent() constructor and dispatch them with EventTarget.dispatchEvent(). Handlers are attached either declaratively in the HTML template (onnextpage={handleNext}) or in JavaScript with this.template.addEventListener().
this.dispatchEvent(
new CustomEvent('nextpage', {
bubbles: true,
composed: true,
cancelable: false,
detail: { value: this.selectedValue }
})
);
The detail property is always an object and is how you carry data with the event.
Q410. How do two Lightning web components communicate when they are not in the same DOM tree?
There are two options for components that have no parent-child relationship.
A singleton JavaScript library that follows the publish-subscribe pattern (the pubsub module). One component publishes an event, other components subscribe to receive and handle it. pubsub is just a JavaScript service component containing fireEvent, registerListener and unregisterListener methods, and it is the LWC equivalent of an Aura application event. Its big limitation is that it only works within a single Lightning page.
A Lightning message channel (Lightning Message Service). The advantage over pubsub is that message channels are not restricted to a single page - any component in a Lightning Experience application that listens on the channel updates when it receives a message, in any tab or pop-out window.
For components that are in the same DOM tree:
Parent to child - pass data down through public @api properties: <c-account-title key={account.Id} account={account}></c-account-title>.
Child to parent - dispatch a custom event: this.dispatchEvent(new CustomEvent('nextpage')); in the child, and handle it on the parent with <c-child-component onnextpage={handleProductChange}>.
Q411. What is Lightning Message Service (LMS) and what can it do that pubsub cannot?
LMS lets you communicate between Aura components, Lightning web components and Visualforce pages, including components in the utility bar.
It is the first Salesforce technology that enables Visualforce pages to communicate with Lightning components anywhere in Lightning Experience, including utility items.
It is based on a metadata type called Lightning Message Channel. You need a message channel to access the Lightning Message Service API.
In LWC, import the channel with the scoped module @salesforce/messageChannel/MyMessageChannel__c.
In Visualforce, use the global variable $MessageChannel.
In Aura, use lightning:messageChannel in your component.
Unlike pubsub, a message channel is not restricted to a single Lightning page, so subscribers anywhere in the app receive the message.
Q412. Show an example of using Lightning Message Service so that an LWC component can send a message to an Aura component.
Create a Lightning Message Channel called MyMessageChannel in the org first, then publish from LWC and subscribe from Aura.
Aura component markup:
<aura:component>
<aura:attribute name="message" type="String" />
<aura:handler name="init" value="{!this}" action="{!c.handleInit}" />
<h2>Aura Component</h2>
<p>Received message: {!v.message}</p>
</aura:component>
Aura controller:
({
handleInit: function (component, event, helper) {
// Subscribe to the message channel
const channel = component.find('myMessageChannel');
const subscription = channel.subscribe(null, function (message) {
// Handle the received message
component.set('v.message', message.getParam('payload').value);
});
component.set('v.subscription', subscription);
}
})
LWC template:
<template>
<h2>LWC Component</h2>
<lightning-button label="Call Aura Component" onclick={handleClick}></lightning-button>
</template>
LWC JavaScript:
import { LightningElement } from 'lwc';
import { createMessageContext, releaseMessageContext, publish, APPLICATION_SCOPE } from 'lightning/messageService';
import MY_MESSAGE_CHANNEL from '@salesforce/messageChannel/MyMessageChannel__c';
export default class MyComponent extends LightningElement {
messageContext = createMessageContext();
handleClick() {
// Publish a message to the Aura component
const message = {
payload: {
value: 'Hello from LWC!'
}
};
publish(this.messageContext, MY_MESSAGE_CHANNEL, message);
}
disconnectedCallback() {
// Release the message context when the component is disconnected or destroyed
releaseMessageContext(this.messageContext);
}
}
When the button is clicked, the LWC publishes Hello from LWC! on the channel and the Aura component sets it into v.message. Both components must be placed on a Lightning page for the communication to happen.
Q413. What are the main differences between Aura components and Lightning Web Components?
Aura and LWC share three platform services: Security (Locker), Lightning Data Service and the base Lightning components. They differ in what the framework itself is built on.
Aura uses LWC uses
--- ---
Custom component model Web components
Custom templates Templates
Custom components Custom elements
Rendering optimization Shadow DOM
Custom modules Modules
Custom events Standard events
Other practical differences:
LWC component tags use a hyphen separator (<c-my-component>), Aura uses a colon (<c:myComponent>).
An Aura component can contain an LWC component, but an LWC component cannot contain an Aura component. To call an LWC from Visualforce the chain is VF > Aura > LWC, and the Aura app must extend ltng:outApp.
LWC runs natively on modern browsers, so it is much faster; Aura still supports features that LWC does not, which is why both frameworks coexist.
LWC cannot be developed in the Developer Console - use VS Code with Salesforce DX.
LWC relies on autowiring: all files in the bundle share the folder name (myComponent.html, myComponent.js, myComponent.css, plus the .js-meta.xml).
{ } curly-brace data binding in the template binds directly to the property in the JavaScript class.
Q414. What are the decorators available in Lightning Web Components and what does each one do?
LWC has three decorators, imported from the lwc module.
@api - marks a property or method as public. Parent components can set it, and it is exposed to Lightning App Builder when declared in targetConfigs. Public properties are reactive: the component re-renders when the value changes.
@track - marks a private field so that changes to the contents of an object or array are tracked. Since Spring '20 all fields are reactive by default, so @track is only needed for deep mutation of objects and arrays.
@wire - reads Salesforce data through a wire adapter or an Apex method. Example: @wire(getContactList) contact; for a wired property, or a wired function that receives { error, data }.
Related ES6 import syntax used in a component:
import { LightningElement, api, track, wire } from 'lwc';
import NAME_FIELD from '@salesforce/schema/Account.Name'; // a field
import ACCOUNT_OBJECT from '@salesforce/schema/Account'; // an object
import getContactList from '@salesforce/apex/ContactController.contactList'; // an Apex method
Getters (get myFunc() { ... }) are used to compute derived values that the HTML template can then reference.
Q415. What are the requirements for an Apex method to be callable from a Lightning web component?
The method must be static and public or global.
It must be annotated with @AuraEnabled immediately before the method definition. That annotation makes the method available to both Lightning web components and Aura components.
Add @AuraEnabled(cacheable=true) to allow the client to cache the result. A cacheable method must not perform any DML - when a method is cacheable, DML operations are not allowed.
Import it into JavaScript with import methodName from '@salesforce/apex/ClassName.methodName';.
There are two ways to call it: wire the method (declarative, cached, refreshable with refreshApex) or call it imperatively (you control when it runs and it can perform DML).
To refresh data that was cached by a wired Apex method, call the refreshApex() function from @salesforce/apex.
Q416. How do you wire an Apex method to a property in an LWC and pass a reactive parameter to it?
import { LightningElement, api, wire } from 'lwc';
import getContactsBornAfter from '@salesforce/apex/ContactController.getContactsBornAfter';
export default class WireApexProperty extends LightningElement {
@api minBirthDate;
@wire(getContactsBornAfter, { birthDate: '$minBirthDate' })
contacts;
}
Line 2: import the getContactsBornAfter function from the ContactController Apex class. This points to the corresponding Apex method.
Line 4: define an @api minBirthDate property. When you use this component in your code, or expose a FlexiPage attribute, you can pass a date to it.
Line 5: the @wire decorator receives two parameters - the Apex method to call and the parameters the adapter needs (birthDate). $minBirthDate is passed as a reactive variable (note the leading $).
Line 6: the result is stored in the contacts property.
Because $minBirthDate is reactive, every time its value changes the Apex method runs again and provisions new data, either from the Lightning Data Service cache or from the server.
The wired property receives an object with data and error; a wired function receives the same shape:
@wire(testName)
wireData({ error, data }) { // the wired function receives either error or data
if (data) {
this.records = data;
}
if (error) {
this.error = error;
}
}
Q417. How do you call an Apex method imperatively from a Lightning web component?
Import the method and invoke it like a function; it returns a Promise.
import { LightningElement, api, wire } from 'lwc';
import getContactsBornAfter from '@salesforce/apex/ContactController.getContactsBornAfter';
export default class CallApexImperative extends LightningElement {
@api minBirthDate;
handleButtonClick() {
getContactsBornAfter({ // imperative Apex call
birthDate: this.minBirthDate
})
.then(contacts => {
// code to execute if related contacts are returned successfully
})
.catch(error => {
// code to execute if related contacts are not returned successfully
});
}
}
Use imperative calls when you need to control when the call happens (for example on a button click), when the Apex method performs DML, or when you want to create/update/delete multiple records. Parameters are passed as a single object whose keys match the Apex parameter names, and this is required to read component fields (this.minBirthDate).
Q418. How do you handle server errors in a Lightning web component?
Errors thrown by LDS wire adapters, LDS functions and Apex calls have specific structures, so the standard practice is to normalise them with a reduceErrors helper (from the c/ldsUtils module in the lwc-recipes sample app). How you handle them depends on how you are calling the server.
Errors on wired properties - define a getter, which stays reactive:
import { reduceErrors } from 'c/ldsUtils';
@wire(getRelatedContacts, { accountId: '$recordId' })
contacts;
get errors() {
return (this.contacts.error) ? reduceErrors(this.contacts.error) : [];
}
Every time this.contacts.error changes, the getter updates the value of the errors property, because of reactivity.
Errors on wired functions - handle the error member each time the function is provisioned:
import { reduceErrors } from 'c/ldsUtils';
@wire(getRelatedContacts, { accountId: '$recordId' })
wiredContacts({ data, error }) {
if (error) {
this.errors = reduceErrors(error);
}
}
Errors when calling a function imperatively - handle the rejected promise:
import { reduceErrors } from 'c/ldsUtils';
handleButtonClick() {
getRelatedContacts({
accountId: this.recordId
})
.then(contacts => {
// code to execute if the promise is resolved
})
.catch(error => {
this.errors = reduceErrors(error); // code to execute if the promise is rejected
});
}
Q419. Which Lightning Data Service solution should you use for each data use case in LWC?
View or edit a record, where field positions are determined by the component - lightning-record-form.
View a record, choosing which fields to include and where to position them (standard rendering or your own) - lightning-record-view-form.
Edit a record, choosing which fields to include and where to position them, with your own rendering and values - lightning-record-edit-form.
Read data for one or more records - the LDS wire adapters getRecord or getRecords.
Create, edit or delete one record - the LDS functions createRecord, updateRecord or deleteRecord. They can be combined, but each operation runs in an independent transaction.
Create, edit or delete multiple records - call Apex imperatively.
Read metadata for one or more objects - the wire adapters getObjectInfo or getObjectInfos.
Read a related list's metadata or records - getRelatedListInfo and getRelatedListRecords (or the batch versions).
Read a list view's metadata - getListInfoByName (or the batch version).
Anything not covered above - call Apex with @wire or imperatively.
The LDS stack is: Browser > Lightning Web Components > Lightning Data Service > Server > User Interface API > Database. LDS handles field-level security, sharing and the record cache for you, which is why it is preferred over Apex whenever it fits.
Q420. What does the LWC configuration file (.js-meta.xml) control, and how do you expose a property to Lightning App Builder?
The *.js-meta.xml configuration file controls where the component can be used and what an admin can configure.
<isExposed>true</isExposed> - lets you use the component in Lightning App Builder.
<target> - lets you add the component to a particular kind of page (app page, home page, record page, and so on).
<targetConfigs> - lets you set the component's design properties (for example a name property) in Lightning App Builder, and restrict the component to particular objects.
<targetConfigs>
<targetConfig targets="lightning__AppPage,lightning__HomePage">
<property name="greeting" type="String" />
<objects>
<object>Account</object>
<object>Contact</object>
</objects>
</targetConfig>
</targetConfigs>
Every property declared here must have a matching @api propertyName in the JavaScript class. <masterLabel> sets the title shown for the component.
Q421. How do you call an external REST API directly from Lightning web component JavaScript using fetch?
Use the browser fetch API in the component's JavaScript. Remember that from LWC JavaScript you cannot call Salesforce APIs other than Lightning Data Service, and the target host must be allowed in CSP Trusted Sites.
JavaScript:
import { LightningElement, track } from 'lwc';
export default class MyComponent extends LightningElement {
@track responseData;
@track requestBody = { key1: 'value1', key2: 'value2' };
handleClick() {
// Make the REST API call
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(this.requestBody)
})
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error('Error: ' + response.status);
}
})
.then((data) => {
// Handle the response data
this.responseData = data;
})
.catch((error) => {
// Handle any errors
console.error(error);
});
}
}
Template:
<template>
<lightning-input label="Request Body" value={requestBody.key1} onchange={handleInputChange}></lightning-input>
<lightning-button label="Fetch Data" onclick={handleClick}></lightning-button>
<template if:true={responseData}>
<ul>
<template for:each={responseData} for:item="item">
<li key={item.id}>{item.name}</li>
</template>
</ul>
</template>
</template>
Q422. How do you build a reusable dynamic data table LWC whose columns and rows are supplied by the parent component?
Keep the table component generic and pass both the column definitions and the data down from the parent as public properties.
Parent template:
<template>
<c-dynamic-table columns={tableColumns} data={tableData}></c-dynamic-table>
</template>
Parent JavaScript with hard-coded data:
import { LightningElement } from 'lwc';
export default class ParentComponent extends LightningElement {
tableColumns = [
{ label: 'Name', field: 'Name' },
{ label: 'Email', field: 'Email' },
{ label: 'Phone', field: 'Phone' }
];
tableData = [
{ Id: '1', Name: 'John Doe', Email: 'john.doe@example.com', Phone: '555-1234' },
{ Id: '2', Name: 'Jane Smith', Email: 'jane.smith@example.com', Phone: '555-5678' },
{ Id: '3', Name: 'Bob Johnson', Email: 'bob.johnson@example.com', Phone: '555-7890' }
];
}
To make it dynamic for a real object, wire an Apex method that returns the records and pass the result through instead:
import { LightningElement, wire } from 'lwc';
import getAccountRecords from '@salesforce/apex/AccountController.getAccountRecords';
export default class ParentComponent extends LightningElement {
tableColumns = [
{ label: 'Account Name', field: 'Name' },
{ label: 'Industry', field: 'Industry' },
{ label: 'Phone', field: 'Phone' }
];
@wire(getAccountRecords)
tableRecords;
}
<template>
<c-dynamic-table columns={tableColumns} records={tableRecords}></c-dynamic-table>
</template>
Inside the child, iterate the rows with for:each and a key, and render each configured field. For a fully generic table you can describe the object in Apex (Schema.getGlobalDescribe() / DescribeFieldResult) and build the column list at runtime.
Aura / Lightning
111 questions
Q423. What is Lightning Data Service?
Lightning Data Service (LDS) lets you load, create, edit or delete a record in your component without requiring Apex code. LDS handles sharing rules and field-level security for you. In addition to simplifying access to Salesforce data, it improves performance and user interface consistency by keeping a shared, cached copy of the record so that all components on the page see the same data and update together. In LWC it is used through the lightning/ui*Api wire adapters (getRecord, createRecord, updateRecord, deleteRecord) and the lightning-record-form family of base components; in Aura it is force:recordData.
Q424. How do you get the current user name and current user profile name in an Aura component without using Apex?
Use force:recordData with the $SObjectType.CurrentUser.Id global value provider and request the spanning Profile.Name field:
<aura:component>
<aura:attribute name="currentUser" type="User"/>
<force:recordData aura:id="recordLoader"
recordId="{!$SObjectType.CurrentUser.Id}"
fields="Profile.Name,Name"
targetFields="{!v.currentUser}"/>
Current User : <strong>{!v.currentUser.Name}</strong>
Current Profile : <strong>{!v.currentUser.Profile.Name}</strong>
</aura:component>
Q425. Where can we use Lightning components?
We can use Lightning components in the following places:
Drag-and-drop components in the Lightning App Builder and Community Builder.
Add Lightning components to Lightning pages.
Add Lightning components to Lightning Experience record pages.
Launch a Lightning component as a quick action.
Override standard actions with Lightning components.
Create stand-alone apps.
Each placement requires the component to implement the matching interface, for example flexipage:availableForAllPageTypes or force:lightningQuickAction.
Q426. How do you build Lightning components?
We can build Lightning components using two programming models: the Lightning Web Components model and the original Aura Components model. Both can coexist on the same page, and an Aura component can contain an LWC (but not the other way round).
Q427. How can you create Lightning record pages in Salesforce, and what are the different types?
We use the Lightning App Builder to create Lightning pages. The three types are:
App Page
Home Page
Record Page
Q428. What options are there for Lightning record page assignment?
Lightning pages can be assigned at three different levels:
The org default.
App default - this overrides the assignment done at the org level.
App, record type, profile - this overrides the assignment done at the org level and at the app level.
Q429. What are attributes in Lightning, and which parameters are required?
Attributes are variables for storing values in a component. An attribute is defined with a name, type, default, description and access, using the <aura:attribute> tag. Only name and type are required parameters.
<aura:attribute name="firstName" type="String" default="John" access="global"/>
Q430. What types of attributes can we use to store values in Aura components?
String
Integer
Boolean
Date
Datetime
Double
Decimal
Long
Array
List
Set
Map
Standard object attribute - for example <aura:attribute name="contactObj" type="Contact"/>
Custom object attribute - for example <aura:attribute name="customObjectList" type="customObject__c[]"/> or <aura:attribute name="customObject" type="customObject__c"/>
Apex class type and Object (generic)
Q431. How can you access a value from an attribute in an Aura component?
Use the value provider v, which represents the component's attribute set:
<aura:attribute name="firstName" type="String"/>
{!v.firstName}
In JavaScript you access it with component.get("v.firstName") and set it with component.set("v.firstName", value).
Q432. How do you call a controller method from JavaScript in an Aura component?
Use component.get("c.methodName") to obtain an action for the Apex method, then set parameters, define a callback and enqueue it.
var action = component.get("c.methodName");
action.setParams({ recordId: recId });
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
console.log(response.getReturnValue());
}
});
$A.enqueueAction(action);
The c. prefix is the value provider for the component's Apex controller, and the Apex method must be annotated with @AuraEnabled.
Q433. Which interface should you use if you want to get the Id of the record from the record detail page?
Use the force:hasRecordId interface. As opposed to using {!v.recordId} only in the markup, implementing this interface makes the current record's Id available and it can be read in the controller with component.get("v.recordId").
Also noted:
Implementing it on the component automatically injects a recordId attribute that is populated with the Id of the record currently in context on the record page.
Q434. Which interface should you use if you want your component to be available for all pages?
Use the flexipage:availableForAllPageTypes interface.
It makes the component appear in the Lightning App Builder component palette for app pages, home pages and record pages alike.
Q435. Which interface should you use if you want to override a standard action?
Use the lightning:actionOverride interface.
A component implementing it can be selected in the object's Buttons, Links and Actions setup to replace a standard action such as New, Edit or View.
Q436. Which interface should you use if you want your component to be available only on the record home page?
Use the flexipage:availableForRecordHome interface.
It exposes the component in the Lightning App Builder only for record pages; it is usually combined with force:hasRecordId so the component receives the record's Id.
Q437. Which interface should you use if you want your component to be used as a tab?
Use the force:appHostable interface.
Implementing it allows the component to be surfaced as a custom tab in Lightning Experience and the Salesforce mobile app.
Q438. Which interface should you use if you want your component to be used as a quick action?
Use the force:lightningQuickAction interface.
It lets the component be selected as a Lightning component action and displays it in a panel with a Cancel button; force:lightningQuickActionWithoutHeader renders it without the header and footer.
Q439. How can you detect a change in an attribute value and call a controller method based on that change in Aura?
Use the change handler:
<aura:handler name="change"
value="{!v.attributeNameWhereValueChangeOccured}"
action="{!c.doinit}"/>
Here attributeNameWhereValueChangeOccured is the attribute name on which the change is being detected.
Q440. How can you call a controller method when a component loads?
Register the init system event with a handler:
<aura:handler name="init" value="{!this}" action="{!c.doInitialization}"/>
value="{!this}" marks it as a system-level init event, and the specified controller function runs after the component is initialised but before it is rendered.
Q441. What are component events?
Component events are events which are fired by child components and handled by the parent component. We use them when we need to pass a value from a child component to a parent component.
They are declared with <aura:event type="COMPONENT">.
They can only be handled by the firing component itself or by a component above it in the containment hierarchy, which keeps their scope local.
Q442. What are application events?
Application events can be fired from any component and can be handled by any component. They do not require any kind of relationship between the components, but these components must be part of a single application.
They are declared with <aura:event type="APPLICATION">.
Because any component can listen, they are best reserved for genuinely application-wide concerns, such as navigating to a specific record.
Also noted:
An application event is fired from an instance of a component and follows a publish-subscribe model. All components that provide a handler for the event are notified. The framework supports the capture, bubble and default phases for the propagation of application events; the capture and bubble phases are similar to DOM event handling patterns.
Q443. Why would you use aura:method?
You use <aura:method> to pass a value from a parent component controller to a child component controller - it defines a method on the child's API so the parent can call it directly instead of firing and handling an event.
ParentComponent.cmp
<aura:component>
<c:ChildComp aura:id="ChildCompId"/>
</aura:component>
ParentComponentController.js
var childComponent = component.find("ChildCompId");
var res = childComponent.chilCompMethod("From parent");
ChildComponent.cmp
<aura:component>
<aura:method name="chilCompMethod" action="{!c.doAction}">
<aura:attribute name="receiveValueFromParent" type="String"/>
</aura:method>
</aura:component>
ChildComponentController.js
({
doAction : function(component, event, helper) {
var params = event.getParam('arguments');
var param1;
if (params) {
param1 = params.receiveValueFromParent;
}
return param1 + " Appended child value";
}
})
Also noted:
The <aura:method> tag is used to define a method as part of a component's API. There is then no need to fire and handle a component event - it allows us to directly invoke a method in the component's client-side controller. It also simplifies the code required for a parent component to call a method on a child component that is part of it.
Q444. How can you enforce field-level security in Lightning components?
Use the base components and data services that respect FLS and sharing automatically: lightning:recordForm, lightning:recordEditForm, lightning:recordViewForm and force:recordData (Lightning Data Service). In LWC the equivalents are lightning-record-form, lightning-record-edit-form, lightning-record-view-form and the lightning/uiRecordApi wire adapters. If you must use Apex, enforce security manually with WITH SECURITY_ENFORCED, WITH USER_MODE, Security.stripInaccessible() or Schema.DescribeFieldResult checks, because Apex runs in system mode by default.
Q445. What is Lightning Out?
If you want to use your component on an external site, you need to use Lightning Out. The best advantage of Lightning Out is that you can use a Lightning component inside a Visualforce page and vice versa. It works by including the Lightning Out JavaScript library on the host page, referencing a Lightning dependency app, and creating the component with $Lightning.createComponent().
Also noted:
Lightning Out is a powerful and flexible feature that allows you to embed Lightning web components and Aura components on any web page outside Salesforce. When using it inside Visualforce you do not need to deal with authentication or configure a connected app, which simplifies the setup considerably; on a fully external site you do need a connected app and an authenticated session.
Q446. What is force:recordData, and what are its advantages?
force:recordData is the Lightning Data Service component that acts as a standard controller for Lightning components. Using it you can create, load, edit and delete a record without writing Apex. If you use force:recordData, it identifies and eliminates duplicate requests going to the server when several components request the same record data, which improves performance. It also handles field-level security and sharing rules, and keeps a single shared cached copy of the record so all components stay in sync.
Q447. What are the phases in component event propagation?
Asked at: Cloud 360
There are two phases in component event propagation:
Bubble phase
Capture phase
By default a handler runs in the bubble phase; you can set phase="capture" on <aura:handler> to handle it in the capture phase instead.
Q448. What are the phases in application event propagation?
There are three phases:
Bubble phase
Capture phase
Default phase
The default phase is unique to application events and is the phase in which handlers run when no phase is explicitly specified.
Q449. How do the bubble phase and the capture phase propagate?
Bubble phase: propagates from bottom to top (from the source component up through its containment hierarchy).
Capture phase: propagates from top to bottom (from the application root down to the source component).
The capture phase always runs first; a handler in either phase can call event.stopPropagation() to halt it.
Q450. What are bound and unbound expressions in Aura?
Bound and unbound expressions are used to perform data binding when a parent component passes a value to a child component's attribute.
Bound expression - {!v.parentAttributeName}:
<aura:component>
<c:ChildComp childAttributeName="{!v.parentAttributeName}"/>
</aura:component>
A change to the value of childAttributeName in the child component also changes the value of parentAttributeName in the parent component, and vice versa (two-way binding).
Unbound expression - {#v.parentAttributeName}:
<aura:component>
<c:ChildComp childAttributeName="{#v.parentAttributeName}"/>
</aura:component>
Changes to the value of childAttributeName in the child component have no effect on the value of parentAttributeName in the parent, and vice versa (one-time binding). Unbound expressions perform better and should be used when two-way binding is not needed.
Q451. What is Aura?
Aura is a framework designed by Salesforce for creating UI components. It is an open-source framework and is the foundation of the original Lightning Component model, providing the component, event and rendering infrastructure.
Q452. What is lightning:navigation and how do we navigate using it?
lightning:navigation is used to navigate to a given PageReference or to generate a URL from a PageReference. To navigate we need to define a PageReference object, which is a JavaScript object that references a page, providing a well-defined structure describing the page type and its corresponding values.
Supported targets we can navigate to:
Lightning Component
Knowledge Article
Named Page
Navigation Item Page
Object Page
Record Page
Record Relationship Page
Web Page
Example - to navigate to a component:
{
"type": "standard__component",
"attributes": {
"componentName": "c__MyLightningComponent"
},
"state": {
"myAttr": "attrValue"
}
}
Then call component.find("navService").navigate(pageReference);
Q453. What is the lightning:isUrlAddressable interface?
If we are navigating to a component, then the target component must implement the lightning:isUrlAddressable interface for the navigation to succeed. It makes the component addressable by a URL of the form /lightning/cmp/c__MyComponent, and any state values passed in the PageReference arrive as a v.pageReference attribute.
Q454. What is Lightning in Salesforce?
Lightning is a collection of tools and technologies for the Salesforce platform. It includes:
# Name Description
--- --- ---
1 Lightning Experience Comprises Lightning Experience, template-based communities and the Salesforce1 mobile app - a set of user interfaces optimised for speed.
2 Lightning Component Framework A JavaScript framework that comes with standard components and enables developers to create reusable components for stand-alone applications, customised Lightning Experience, template-based communities and mobile apps.
3 Lightning App Builder and Community Builder Offer a fast, easy way of building and customising apps with drag-and-drop. The App Builder customises Lightning Experience and the Salesforce1 mobile app; Community Builder customises template-based communities.
4 Lightning Design System (LDS) Makes it possible to build apps that match the look of the Salesforce1 mobile app and Lightning Experience, with modern UX best practices and style guides.
5 Lightning Exchange A section of AppExchange with 70+ partner components to start development with.
Q455. What are components in the Lightning Component framework?
Components act as the functional units of the Lightning Component framework. A reusable, modular section of UI is encapsulated within a component. In terms of granularity, they can range from a single line of text up to an entire application.
Q456. What are the resources in a Lightning (Aura) component bundle?
# Component bundle Description
--- --- ---
1 Component Contains the markup.
2 Controller Handles the events on the client side.
3 Helper Holds the common logic used by different controller methods, avoiding repetition.
4 Style Defines the style of the component.
5 Documentation Records the component's use.
6 Renderer Contains the default rendering behaviour of a component.
7 SVG The icon displayed before the component in the Lightning App Builder.
8 Design Helps component reusability and controls which attributes are exposed to tools such as the Lightning App Builder.
Q457. How does the Salesforce mobile app use Lightning components?
First create a Lightning tab for the Lightning component, then include that tab in the navigation menu (select list) of the Salesforce mobile app, so the newly created tab - and therefore the component - is available on mobile. The component must implement force:appHostable to be usable as a tab.
Q458. Can a Lightning component be used that works with both interfaces - mobile and desktop?
Yes. Lightning components, the Salesforce mobile app and custom standalone apps can be used directly in Lightning Experience as well as in template-based communities. Lightning components can also be used in a Visualforce page (via Lightning Out) for use in Visualforce communities and the Classic environment.
Q459. Does a Lightning component work with Visualforce?
Yes, it does work with Visualforce - a Lightning component can be embedded in a Visualforce page using Lightning Out (<apex:includeLightning/> and $Lightning.createComponent()), and a Visualforce page can be surfaced inside a Lightning component using an iframe.
Q460. Can Lightning be viewed as an MVC framework?
Not really. Lightning is a component-based framework rather than an MVC framework - it is built around composable components with their own markup, client-side controllers and helpers, rather than around a strict model-view-controller separation.
Q461. Which parts of a Lightning component are server-side and which are client-side?
For a Lightning component, the client side is the component markup with its JavaScript controller and helper, and the server side is the Apex controller. JavaScript handles the UI and interaction; Apex handles data access and business logic on the server.
Q462. What are the differences between Lightning components and Visualforce components?
Visualforce components are page-centric and the work is mostly server-based - each interaction typically involves a server round trip and a full or partial page refresh. Lightning components are client-side centric, which accounts for their dynamic, responsive and mobile-friendly nature: the UI is rendered in the browser and only data is fetched from the server.
Q463. Can we create a component that inherits style/CSS from the parent, or must it always be defined in the component?
Yes, we can. Styles can be inherited from a parent component and do not necessarily have to be defined inside the component itself - CSS declared higher up (or in the Salesforce Lightning Design System) cascades into the component in Aura. (In Lightning Web Components, shadow DOM restricts this, so styling is shared through CSS custom properties, SLDS styling hooks or an imported shared CSS module.)
Q464. Is it possible to include one Lightning component inside another?
Yes, it is possible - components are composable, so a component can contain other custom (<c:MyChild/>) and standard components, which is the basis of the component containment hierarchy.
Also noted:
Yes, it is possible. Components are composable - a component can include other components in its markup, which is how complex UIs are assembled from small reusable pieces.
A parent can include a child simply with its tag, e.g. <c:childComponent/>.
Data flows down through attributes, and back up through component events or aura:method.
Q465. What are Aura components, and why do we use the aura: namespace in the code?
Aura components are the self-contained and reusable units of an app - they are the functional units of Aura. Aura is the open-source technology behind Lightning components. The aura: namespace contains the building blocks that help define the components and applications - for example <aura:component>, <aura:attribute>, <aura:handler>, <aura:iteration> and <aura:if>.
Q466. Are there any CSS styles provided by Salesforce for supported Lightning components?
Yes. These are available in the Salesforce Lightning Design System (SLDS), which supplies the CSS framework, design tokens and styling hooks that make custom components match the Lightning Experience look and feel.
Q467. Are Lightning components meant only for mobile apps?
No. With responsive design in mind, Lightning components are mobile-first, but they are not mobile-only. The components help you build responsive apps faster for desktops, tablets and mobile devices alike.
Q468. Is it possible to include external JavaScript/CSS libraries in Lightning components?
Yes. Multiple libraries such as jQuery, Bootstrap and other JavaScript/CSS libraries can be used, provided they are uploaded as a local static resource and loaded with ltng:require (Aura) or loadScript/loadStyle from lightning/platformResourceLoader (LWC). Locker Service / Lightning Web Security restrictions apply to what those libraries can do.
Q469. Is it possible to integrate Lightning components with a framework such as Angular?
It is possible to insert third-party framework code within a Visualforce page, and then embed that Visualforce page inside a Lightning component. That Lightning component can then be used inside other Lightning components and works across the different environments.
Q470. Do you create an app bundle first in order to create a Lightning component?
Not really - the component bundle can be created first. An application bundle (.app) is only needed when you want a stand-alone Lightning app or a dependency app for Lightning Out.
Q471. How do you create a custom Lightning record page in Salesforce (steps)?
Use the Lightning App Builder to add, remove or reorder components on a record page to create a custom view of an object's records.
Yes - you can also customize a record page and assign it to Lightning apps, so users access a custom record page in the context of the app they are working in. Record pages can also be activated for the Salesforce mobile app (phone form factor) through the Activation settings.
Also noted:
Setup > enter "App Builder" in the Quick Find box > select Lightning App Builder > New > Record Page > name the page > select the object (for example Opportunity) > choose a template such as Header, Subheader, Right Sidebar > click Finish. Then drag the required components onto the regions, Save, and Activate to assign it as the org default, app default, or by app/record type/profile.
Q472. How do you find data changes using data handlers in Lightning?
Configure the component to invoke a change handler when the value of one of its attributes changes, using <aura:handler name="change" value="{!v.myAttribute}" action="{!c.handleChange}"/>. When the attribute value changes, the specified controller action is invoked, so you can react to the new value. (In LWC, the equivalent is a reactive getter or a setter on an @api property.)
Q473. How do you trace where a section (for example a quick action) on a Lightning page comes from?
Asked at: Mahindra & Mahindra
Work backwards from the page to the component:
Open the record and choose Setup (gear) > Edit Page to open the Lightning App Builder - it shows every component placed on the page and its API name.
If the section is a quick action, check the object's Buttons, Links and Actions in Object Manager (and the Global Actions list in Setup for a global quick action) to see which action is bound to which Lightning component or Visualforce page.
Inside the markup, a nested custom component appears as a tag such as <c:ACE_BookingLoyalityExchange />, which tells you the child component being imported; follow that name into the Developer Console / VS Code to see its bundle.
Q474. What is the use of the doInit method in an Aura component?
Asked at: Mahindra & Mahindra
It is loaded when the Lightning application or component loads, and it is pretty much similar to a constructor.
It is wired up with the init handler: <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>.
It runs after the component is initialised but before rendering, so it is the usual place to set default attribute values or fire the first server call.
Also noted:
It is typically used to load initial data from the Apex controller and set attribute values before the component renders.
Q475. What is the difference between a component event and an application event in Aura?
Asked at: Appcino
Component event
Fired from an instance of a component and handled by the same component or by a component in its containment hierarchy (a parent/ancestor).
Propagation follows two phases - bubble (child to parent, 1 > 2 > 3) and capture (parent to child, 3 > 2 > 1) - selected with the phase="bubble" or phase="capture" attribute on the handler.
Preferred wherever possible, because the audience of the event is limited and therefore more secure and easier to debug.
<!-- create -->
<aura:event type="COMPONENT" description="Event template">
<aura:attribute name="selected" type="String"/>
</aura:event>
<!-- register on the firing component -->
<aura:registerEvent name="returnSelectedVal" type="c:SelectComponentEvent"/>
<!-- handle on the parent -->
<aura:handler name="returnSelectedVal" event="c:SelectComponentEvent" action="{!c.getSelected}"/>
// fire
var eve = component.getEvent("returnSelectedVal");
eve.setParams({ "selected" : val });
eve.fire();
// read in the handler
var val = event.getParam("selected");
Application event
Used for communication between two components anywhere in the application, even when they are not in the same containment hierarchy.
Follows a publish-and-broadcast model: when the event is fired, every component that handles it is notified.
Because everything can listen to it, an application event is less secure and harder to trace, so use it only when a component event will not do.
<aura:event type="APPLICATION" description="event template">
<aura:attribute name="regionVal" type="String"/>
</aura:event>
<aura:handler event="c:SelectParentApplication" action="{!c.handleAppEvent}"/>
var eve = $A.get("e.c:SelectParentApplication");
eve.setParams({ "regionVal" : val });
eve.fire();
The four steps in both cases are: create the event, register it, fire it, and handle it.
Also noted:
Component event - fired by a child component and handled by a component in the containment hierarchy. It supports the bubble phase (bottom to top) and the capture phase (top to bottom, rarely used).
Application event - can be fired by any component and handled by any component in the app (publish-subscribe). It supports capture, bubble and default phases.
event.stopPropagation(); is called in the controller to stop the event travelling further.
Default phase - the framework executes the default phase from the root node unless preventDefault() was called in the capture or bubble phase. If propagation was not stopped in a previous phase, the root node defaults to the application root; if it was stopped, the root node is set to the component whose handler invoked event.stopPropagation().
Q476. How do you display accounts and their related contacts in an Aura component using custom code?
Asked at: GenPact
Use a parent-child (inner) SOQL query in the Apex controller and iterate over the result in the component:
SELECT Id, Name, (SELECT Id, Name FROM Contacts) FROM Account
Return the list to the component and render it with <aura:iteration>, nesting a second <aura:iteration> over {!account.Contacts}.
Q477. What is the difference between a JavaScript controller and a JavaScript helper in an Aura component?
Asked at: GenPact
The controller handles events raised by the component markup ({!c.methodName}) and should stay thin.
The helper holds the common logic that is shared between controller methods, so code is not repeated. It is called as helper.methodName(component, event, helper).
A helper can also be shared with other components through inheritance, for example <aura:component extends="c:SharingComponent" />.
Q478. A component is working very slowly - how do you improve its performance?
Asked at: GenPact
Check whether it is a device or browser issue first, and remove unnecessary Chrome plugins/extensions.
Bulkify the code and remove unnecessary/dead code.
Use the Lightning Data Service (LDS) (force:recordData, lightning-record-form) instead of custom Apex, so the record is cached and shared between components.
Reduce the number of server round trips, cache results with @AuraEnabled(cacheable=true), and avoid unnecessary re-renders.
Q479. What is the life cycle of an event in Salesforce Lightning (Aura)?
Asked at: Cognizant
Component Event: the parent or container component instance that fired the event is identified. Life cycle: Event Creation (producer) > Event Propagation > Event Handling (consumer) > Event Destruction.
Application Event: any component can have an event handler for this event. Life cycle: Event Creation (producer) > Event Propagation > Event Handling (consumer) > Event Destruction.
Differences between them:
A component event follows the parent-to-child or child-to-parent relationship, whereas an application event is used to communicate between components that are not directly related in the hierarchy.
A component event follows a bubbling or capturing phase within the component hierarchy, whereas an application event propagates throughout the entire Lightning application.
Also noted:
render() - produces the DOM for the component
rerender() - updates the DOM when the underlying data changes
afterRender() - runs after the DOM has been created, used to attach behaviour
unrender() - removes the DOM when the component is destroyed
Q480. Which framework does Salesforce Lightning (Aura) follow?
Asked at: Accenture, Cognizant
The Lightning Component architecture - a component-based, client-server architecture where the client side is JavaScript (controller, helper, renderer) and the server side is an Apex controller, with the two communicating over asynchronous server actions.
Also noted:
Aura is an open-source, event-driven, component-based UI framework that uses a stateful client and stateless server architecture. Lightning Web Components later added a second, standards-based programming model alongside it.
Q481. What are design attributes in Aura?
Asked at: Cognizant
Design attributes are the component attributes you expose to declarative tools such as the Lightning App Builder and Community Builder.
The attribute is first declared with <aura:attribute name=".." type=".."/> in the component.
It is then exposed in the design resource (componentName.design):
<design:component>
<design:attribute name="greeting" label="Greeting" description="Text shown to the user"/>
</design:component>
Only attributes listed in the design file can be edited by an admin in the App Builder.
Q482. What are the interfaces available in an Aura component?
Asked at: Cognizant
Interfaces are declared in the implements attribute of <aura:component> and determine where the component can be used:
<aura:component implements="lightning:isUrlAddressable,
force:appHostable,
flexipage:availableForAllPageTypes,
force:hasRecordId,
flexipage:availableForRecordHome,
lightning:actionOverride,
forceCommunity:availableForAllPageTypes,
force:lightningQuickAction"
controller="ACE_BookingVehicleExchangeController"
extends="c:otherComponent">
force:appHostable - use the component as a tab.
flexipage:availableForAllPageTypes - available on all Lightning pages.
flexipage:availableForRecordHome - record home pages only.
force:hasRecordId - receive the current record Id.
lightning:actionOverride - override a standard action.
force:lightningQuickAction - use as a quick action.
forceCommunity:availableForAllPageTypes - available in Experience/Community Builder.
lightning:isUrlAddressable - the component can be navigated to by URL.
Q483. What are the navigate-to-URL methods in Lightning Aura?
Asked at: Cloud 360
Answer supplied - source left blank.
Use the lightning:navigation service (the modern approach) or the older force:navigateToURL event.
<lightning:navigation aura:id="navService"/>
// PageReference for an external/relative URL
var pageRef = {
type: 'standard__webPage',
attributes: { url: 'https://www.salesforce.com' }
};
component.find("navService").navigate(pageRef);
// generateUrl(pageRef, callback) returns the URL instead of navigating
Older events, still supported in Aura:
force:navigateToURL - navigate to a relative or absolute URL.
force:navigateToSObject - open a record.
force:navigateToList - open a list view.
force:navigateToComponent - open a component.
force:navigateToObjectHome - open an object home page.
Q484. How do you redirect to another URL from a JavaScript controller?
Asked at: Cloud 360
Answer supplied - source left blank.
In an Aura JavaScript controller use the navigation service or the force:navigateToURL event:
var urlEvent = $A.get("e.force:navigateToURL");
urlEvent.setParams({ "url": "/lightning/o/Account/home" });
In an LWC JavaScript controller use NavigationMixin:
this[NavigationMixin.Navigate]({
type: 'standard__webPage',
attributes: { url: 'https://www.salesforce.com' }
});
Plain window.open(url) / window.location.href = url also works but is not Locker-Service friendly for internal navigation and is discouraged.
Q485. If a child component fires an event with a value X, does it go to the parent component or to the super parent component?
Asked at: Cloud 360
For a component event, it goes to the parent component - the event travels up the containment hierarchy and is handled by the nearest component that registers a handler for it. If that handler calls event.stopPropagation() it goes no further; otherwise bubbling continues up towards the super parent.
Q486. How do you expose a component to a community using interfaces?
Asked at: Cloud 360
Implement the community interface on the component:
<aura:component implements="forceCommunity:availableForAllPageTypes" access="global">
The component must have access="global" to be usable in Community/Experience Builder.
Add a .design file and mark an attribute as required so that it automatically appears (and must be filled in) in the Community Builder property panel.
Q487. What is the use of an attribute in an Aura component?
An attribute is like a variable. If you want to store data, then you should use an attribute.
It is declared with <aura:attribute name="accName" type="String" default="Test"/>.
It supports types such as String, Boolean, Integer, Date, sObject, List, Map and custom Apex classes, and is read in markup through the v value provider, e.g. {!v.accName}.
Q488. What is a bound expression in Aura?
With a bound expression you are able to get the new value, because the data is kept in sync between parent and child.
Syntax:
{!v.attributeName}
Any change made to the attribute in the child component is reflected back in the parent component, and vice versa.
Q489. What is an unbound expression in Aura?
With an unbound expression you will not be able to get the new value, because the data is not kept in sync.
Syntax:
{#v.attributeName}
The value is passed only once at initialisation; later changes on either side are not propagated to the other component. This is cheaper at runtime than a bound expression.
Also noted:
Since no data binding has to be maintained between the parent and the child, unbound expressions ({#v.attr}) are cheaper at runtime and improve performance for display-only data.
Q490. What is the use of the @AuraEnabled annotation?
If you want to access Apex data in a Lightning application, then you must write the @AuraEnabled annotation on the method. You will not be able to access the data in a Lightning application without @AuraEnabled.
It exposes an Apex method or property to Aura components and Lightning web components.
Methods must be public/global and static to be callable from a component.
Adding @AuraEnabled(cacheable=true) caches the result on the client, but the method must then only read data, not mutate it.
Q491. What is the use of the global action $A.enqueueAction in a Lightning controller?
$A.enqueueAction(action) is used to execute the server-side logic.
It adds the action to the queue rather than running it immediately; the framework then sends queued actions to the server in a single batched request (a process called boxcarring).
It is the last step after component.get("c.method"), action.setParams() and action.setCallback().
Q492. Can we write a void method that is called from a Lightning component?
No.
An @AuraEnabled method that is called from a component is expected to return a value to the callback, so a void return type gives you nothing in response.getReturnValue(). Return at least a String or Boolean status so the client can tell what happened. (Note: a void @AuraEnabled method does technically compile and execute, but since the callback receives null, it is not a usable pattern — hence the answer "No" in practice.)
Q493. How do you get the response value from a callback in an Aura component?
Use response.getReturnValue().
action.setCallback(this, function(response) {
var result = response.getReturnValue();
component.set("v.accounts", result);
});
This returns whatever the @AuraEnabled Apex method returned, deserialized into JavaScript.
Q494. How do you get the state of a server response in a Lightning controller?
Use response.getState().
It returns one of SUCCESS, ERROR, INCOMPLETE or NEW, so you normally branch on it inside the callback:
var state = response.getState();
if (state === "SUCCESS") {
// handle result
} else if (state === "ERROR") {
// handle errors from response.getError()
}
Q495. Why is using a helper method a best practice in Lightning?
It is used for reusability.
The helper holds the actual logic, while the controller only handles the event and delegates to the helper.
Helper functions can be called from the controller, the renderer and from other helper functions, so the same code is shared instead of being duplicated in multiple controller handlers.
Q496. What is reusability in Lightning, and how does a helper achieve it?
Reusability means you are able to access a value or logic from one method in another method.
method1: function(component) {
var name = 'sfdcscenarios';
this.method2(name);
},
method2: function(name) {
// reusability
console.log('name from method1 is ' + name);
}
Because helper functions can call each other with this.methodName(), common logic is written once and invoked from many places.
Q497. Is reusability possible in the controller?
No. It happens in the helper.
A controller function cannot call another controller function directly, so shared logic has to be moved into the helper, where any function can call any other with this.functionName().
Q498. How many types of tags do we have in Lightning?
Two sets of base tags:
ui tags (for example <ui:inputText>, <ui:button>) — the older, basic components.
lightning tags (for example <lightning:input>, <lightning:button>) — the newer components that already follow the Salesforce Lightning Design System and are the recommended choice.
Q499. What does extends="force:slds" do in a Lightning application?
It makes the application acquire the properties (styling) of the Salesforce Lightning Design System.
Adding it to <aura:application extends="force:slds"> loads the SLDS stylesheet so that SLDS classes such as slds-box and slds-button render correctly inside a standalone Lightning app.
Q500. What happens if you do not put extends="force:slds" in a Lightning application?
It will look like a normal HTML file.
Without the SLDS stylesheet, all the slds-* classes in the markup resolve to nothing, so the app renders with default, unstyled browser formatting.
Q501. What is v in an attribute expression?
v is a value provider. If you want to access the value of an attribute, you use {!v.attrName} or {#v.attributeName}.
v gives access to the component's own attributes.
The related provider c gives access to the component's controller actions, for example {!c.handleClick}.
Q502. What is a Lightning component bundle?
A Lightning (Aura) component bundle is the set of related resources created with the component. It contains:
Component (the .cmp markup)
Controller (client-side JavaScript)
Helper
Design
SVG
Documentation
Style (CSS)
Renderer
Only the component markup is mandatory; the other resources are created as needed.
Q503. What is a renderer in an Aura component bundle?
If you want to override the standard rendering mechanism in Salesforce Lightning, then you use the renderer.
It lets you hook into the rendering lifecycle with functions such as render(), rerender(), afterRender() and unrender(), which is useful when you need to do custom DOM manipulation after the framework has rendered the component.
Q504. What are the types of events in Salesforce Lightning?
There are three types:
Component events — fired by a child component and handled by itself or a component above it in the containment hierarchy.
Application events — fired by any component and handled by any component in the application.
System events — fired automatically by the framework during the component lifecycle (for example init, render, aura:doneRendering).
Q505. How do you use an Aura (Lightning) component inside a Visualforce page?
1. Create a Lightning application that extends ltng:outApp and declares the components it makes available as dependencies:
<aura:application access="GLOBAL" extends="ltng:outApp">
<aura:dependency resource="c:LcForVfPage"/>
<aura:dependency resource="c:TestComponent"/>
</aura:application>
ltng:outApp is the interface used to reference the app from a Visualforce page; it applies SLDS styling by default. Use ltng:outAppUnstyled if you do not want the Lightning design applied.
2. In the Visualforce page add the Lightning JavaScript library and create the component:
<apex:page>
<apex:includeLightning/>
<div id="lightningvf"/>
<script>
$Lightning.use("c:MyLightningOutApp", function() {
$Lightning.createComponent(
"c:LcForVfPage",
{ recordId : "{!$CurrentPage.parameters.recId}" },
"lightningvf",
function(cmp) { }
);
});
</script>
</apex:page>
<apex:includeLightning/> adds the JavaScript library required to host Lightning components in Visualforce.
$Lightning.use() can be called multiple times on a page, but every call must reference the same Lightning dependency application.
$Lightning.createComponent() can be called multiple times, so more than one component can be added to the page.
{!$CurrentPage.parameters.recId} is how you read the record Id out of the URL and pass it in.
Q506. How do you pass parameters to a controller (Apex) method from an Aura component?
Use action.setParams().
var action = component.get("c.getAccount");
action.setParams({ accId: component.get("v.recordId") });
$A.enqueueAction(action);
The key names in the map must match the @AuraEnabled method's parameter names exactly.
Q507. How do you navigate from one Lightning component to another Lightning component?
Use the e.force:navigateToComponent event.
var evt = $A.get("e.force:navigateToComponent");
evt.setParams({
componentDef: "c:targetComponent",
componentAttributes: { recordId: recId }
});
evt.fire();
(Note: force:navigateToComponent is a reserved/unsupported event; in modern orgs the supported approach is the lightning:navigation service with a standard__component page reference.)
Q508. How do you go from one Lightning page to another Lightning page on a click?
Fire the e.force:navigateToURL event.
var urlEvent = $A.get("e.force:navigateToURL");
urlEvent.setParams({ "url": "/lightning/o/Account/home" });
It navigates the user to any relative or absolute URL from a click handler.
Q509. What are the best practices for Lightning development?
Do not put too many console logs in your code.
Use the Salesforce Lightning Design System for a consistent UI.
Use Lightning Data Service to avoid server calls for DML operations.
Use unbound expressions if the data across components does not need to stay in sync.
Before using a third-party library, re-evaluate whether you really need it. DOM manipulation libraries (like jQuery) and UI libraries (like Bootstrap or jQuery UI) in particular may no longer be needed with the Lightning Component Framework.
When possible, use the sprite-based Lightning Design System icons (<lightning:icon> and <lightning:buttonIcon>) instead of custom icons.
Salesforce is slower for users who have debug mode enabled, so do not enable it in production.
Where appropriate, pass data between components (using attributes, events or methods) rather than retrieving the same data separately in each component.
When calling the server, limit the columns and rows of the result set: select only the columns you need, set a LIMIT on the query, and provide a paging mechanism instead of returning a huge number of rows at once.
Consider combining several requests (actions) into a single composite request.
Cache data when possible. Client-side caching significantly reduces server round trips: a storable action is a server action whose response is stored in the client cache, so subsequent requests for the same server method with the same arguments are served from that cache.
Limit the number of event handlers in your component. Multiple event handlers mean the component is busy listening for event changes, which adds performance overhead.
Always prefer a component event over an application event when possible. Component events can only be handled by components above them in the containment hierarchy, so their usage stays localised. Application events are best for something handled at the application level, such as navigating to a specific record, and allow communication between components that have no containment relationship.
Use helper methods for reusable logic.
To improve runtime performance, set @AuraEnabled(cacheable=true) to cache method results on the client. To set cacheable=true, the method must only get data — it cannot mutate data.
Q510. What is lightning:overlayLibrary in a Salesforce Lightning component?
To create a modal box we use lightning:overlayLibrary. To use it, include the tag <lightning:overlayLibrary aura:id="overlayLib"/> in the component, where aura:id is a unique local id.
The modal has a header, body and footer, all of which are customizable.
You then call component.find("overlayLib").showCustomModal({...}) from the controller to display it, and it can also show notices and pop-ups.
Q511. Is there any limit on how many components you can have in one application?
There is no limit.
You can nest as many components as needed, though for performance you should still keep the component tree and the number of event handlers reasonable.
Q512. Are Lightning components replacing Visualforce?
No.
Both continue to be supported. Visualforce remains the right choice for things like PDF generation, email templates and full page-level control, while Lightning components are the model for building modern, responsive UI in Lightning Experience.
Q513. What are the advantages of Lightning?
The benefits include an out-of-the-box set of components, an event-driven architecture, and a framework optimized for performance.
Out-of-the-box component set — comes with a ready set of components to kick-start building apps, so you don't have to spend time optimizing your apps for different devices; the components take care of that for you.
Rich component ecosystem — create business-ready components and make them available in the Salesforce mobile app, Lightning Experience and Communities.
Performance — uses a stateful client and stateless server architecture that relies on JavaScript on the client side to manage the UI. It intelligently uses your server, browser, devices and network so you can focus on the logic and interactions of your apps.
Event-driven architecture — better decoupling between components.
Faster development — empowers teams to work faster with out-of-the-box components that function seamlessly on desktop and mobile devices.
Device-aware and cross-browser compatible — responsive design, supporting the latest browser technology such as HTML5, CSS3 and touch events.
Q514. How can we access a custom label in Lightning?
Use the $Label global value provider.
Syntax:
$A.get("$Label.namespace.labelName");
In markup you can also write {!$Label.c.labelName}, and in a Lightning web component you import it: import myLabel from '@salesforce/label/c.labelName';
Q515. How can we use a component in the Community Builder?
Implement the forceCommunity:availableForAllPageTypes interface on the component.
The component must also be marked as available in the Community Builder in its design/meta configuration so it appears in the drag-and-drop palette.
Q516. When should we use aura:handler in a Salesforce Lightning component? Can you write the syntax?
In a Lightning component, <aura:handler ...> is used to handle standard and custom events.
We can create our own custom Lightning event and also use standard events.
A standard Lightning event is automatically fired when the related event fires.
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
Q517. Can we access one JavaScript controller method from another controller method in a Salesforce Lightning component?
No, we can't access one JavaScript controller method from another controller method.
Q518. Can we access one JavaScript helper method from another helper method in a Lightning component?
Yes, we can access one helper method from another helper method.
Q519. How do you add a Lightning button in Salesforce Lightning?
Use the lightning:button tag to add a button in the component.
Example:
<lightning:button variant="base" label="Base" title="Base action" onclick="{! c.handleClick }"/>
Q520. How do you display success, warning, error and info messages on a Lightning page? Can you write sample code?
Use the standard force:showToast event and set its type to info, success, error or warning.
Component:
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes">
<div>
<lightning:button label="Information"
variant="brand"
onclick="{!c.showInfo}"/>
<lightning:button label="Error"
variant="destructive"
onclick="{!c.showError}"/>
<lightning:button label="Warning"
variant="neutral"
onclick="{!c.showWarning}"/>
<lightning:button label="Success"
variant="success"
onclick="{!c.showSuccess}"/>
</div>
</aura:component>
JavaScript controller:
({
showInfo : function(component, event, helper) {
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
title : 'Info',
message: 'This is an information message.',
duration:' 5000',
key: 'info_alt',
type: 'info',
mode: 'dismissible'
});
},
showSuccess : function(component, event, helper) {
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
title : 'Success',
message: 'This is a success message',
duration:' 5000',
key: 'info_alt',
type: 'success',
mode: 'pester'
});
},
showError : function(component, event, helper) {
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
title : 'Error',
message:'This is an error message',
duration:' 5000',
key: 'info_alt',
type: 'error',
mode: 'pester'
});
},
showWarning : function(component, event, helper) {
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
title : 'Warning',
message: 'This is a warning message.',
duration:' 5000',
key: 'info_alt',
type: 'warning',
mode: 'sticky'
});
}
})
Q521. How do you display an alert message in a Lightning component? Can you write sample code?
Component:
<aura:component >
<lightning:button label="Submit" variant="brand" onclick="{!c.handleClick}"/>
</aura:component>
JavaScript controller:
({
handleClick : function(component, event, helper) {
alert('Alert message');
}
})
Q522. How do you set a value to an attribute? Can you write a simple example?
Use component.set("v.attributeName", value) in the JavaScript controller.
Component:
<aura:component >
<aura:attribute name="booleanvar" type="boolean" default="false"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
value is:{!v.booleanvar}
</aura:component>
JavaScript controller:
({
doInit:function(component,event,helper){
component.set("v.booleanvar",true)
}
})
Q523. How do you display data in a Lightning component? Can you write the code?
Apex controller:
public class contactcontroller {
@AuraEnabled
public static list<contact> condata()
{
list<contact> col=[select id,LastName,Email,Phone from contact ];
return col;
}
}
Component:
<aura:component controller="contactcontroller">
<aura:attribute name="conlist" type="list"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<table class="slds-table slds-table_cell-buffer slds-table_bordered">
<tr >
<td>
LastName
</td>
<td>
</td>
<td>Phone</td>
</tr>
<aura:iteration items="{!v.conlist}" var="con">
<tr>
<td>
{!con.LastName}
</td>
<td>
{!con.Email}
</td>
<td >
{!con.Phone}
</td>
</tr>
</aura:iteration>
</table>
</aura:component>
JavaScript controller:
({
doInit :function(component, event, helper)
{
var action=component.get("c.condata");
action.setCallback(this,function(response){
var responseval=response.getReturnValue();
var state=response.getState();
console.log('state is'+state);
if(state==='SUCCESS')
{
component.set("v.conlist",responseval);
}
else
{
console.log('unable to process the data');
}
});
$A.enqueueAction(action);
}
})
Order of execution in Lightning:
Step 1: We call the controller method in JavaScript.
var action=component.get("c.displayContacts");
Step 2: We pass the parameters.
action.setParams({
});
Step 3: $A.enqueueAction(action) sends the request to the server. More precisely, it adds the call to the queue of asynchronous server calls.
$A.enqueueAction(action);
Step 4: action.setCallback() sets a callback action that is invoked after the server-side action returns.
Q524. How do you display contact records based on the selected AccountId? Can you write the Lightning code?
Apex controller:
public class accconbaes {
@AuraEnabled
public static List<Account> displayAccounts()
{
List<Account> acclist=[select Id,Name,Site from Account LIMIT 10];
return acclist;
}
@AuraEnabled
public static List<Contact> displayContacts(String searchkey)
{
System.debug('Value of the AccountId'+searchkey);
List<Contact> conlist=[select Id,AccountId,LastName,Email from Contact where AccountId=:searchkey];
return conlist;
}
}
Component:
<aura:component controller="accconbaes">
<aura:attribute name="acclist" type="list"/>
<aura:attribute name="conlist" type="list"/>
<aura:attribute name="isDisplay" type="boolean" default="false"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<table class="slds-table slds-table_cell-buffer slds-table_bordered">
<tr>
<td>Action</td>
<td>Id</td>
<td>Name</td>
</tr>
<aura:iteration items="{!v.acclist}" var="acc">
<tr>
<td>
<lightning:input type="radio" name="radioButon" value="{!acc.Id}" onchange="{!c.showData}"/>
</td>
<td>
{!acc.Id}
</td>
<td>
{!acc.Name}
</td>
</tr>
</aura:iteration>
</table>
<aura:if isTrue="{!v.isDisplay}">
<table class="slds-table slds-table_cell-buffer slds-table_bordered">
<tr>
<td>Id</td>
<td>LastName</td>
</tr>
<aura:iteration items="{!v.conlist}" var="con">
<tr>
<td>
{!con.Id}
</td>
<td>
{!con.LastName}
</td>
</tr>
</aura:iteration>
</table>
</aura:if>
</aura:component>
JavaScript controller:
({
doInit : function(component, event, helper) {
var action=component.get("c.displayAccounts");
action.setCallback(this,function(response){
var state=response.getState();
var responseval=response.getReturnValue();
if(state==='SUCCESS')
{
component.set("v.acclist",responseval);
}
else
{
alert('unable to process the request');
}
});
$A.enqueueAction(action);
},
showData:function(component,event,helper){
var currentAccountId=event.getSource().get("v.value");
component.set("v.isDisplay",true);
var action=component.get("c.displayContacts");
action.setParams({
searchkey:currentAccountId
});
action.setCallback(this,function(response){
var state=response.getState();
var responseval=response.getReturnValue();
if(state==='SUCCESS')
{
component.set("v.conlist",responseval);
}
else
{
alert('unable to process the request');
}
});
$A.enqueueAction(action);
}
})
Application:
<aura:application extends="force:slds" >
<c:acccon></c:acccon>
</aura:application>
Q525. How do you implement a dynamic search in a Salesforce Lightning component? Can you write an example?
Apex controller:
public class accconbaes {
@AuraEnabled
public static List<Account> displayAccounts(String searchkey)
{
String searchword='%'+searchkey+'%';
System.debug('userinput'+searchword);
List<Account> returnlist=new List<Account>();
for(Account acc:[select Id,Name,Site from Account where Name like:searchword])
{
returnlist.add(acc);
}
return returnlist;
}
}
Component:
<aura:component controller="accconbaes">
<aura:attribute name="accName" type="String"/>
<aura:attribute name="acclist" type="list"/>
<aura:attribute name="isDisplay" type="boolean" default="false"/>
<lightning:input type="text" label="AccountName" value="{!v.accName}" onchange="{!c.handleSearch}" style="width:20%;"/>
Records size:{!v.acclist.length}
<aura:if isTrue="{!v.isDisplay}">
<aura:if isTrue="{!v.acclist.length!=0}">
<table class="slds-table slds-table_cell-buffer slds-table_bordered">
<tr>
<td>Name</td>
</tr>
<aura:iteration items="{!v.acclist}" var="acc">
<tr>
<td>
{!acc.Name}
</td>
</tr>
</aura:iteration>
</table>
</aura:if>
</aura:if>
</aura:component>
JavaScript controller:
({
handleSearch : function(component, event, helper) {
component.set("v.isDisplay",true);
var action=component.get("c.displayAccounts");
action.setParams({
searchkey:component.get("v.accName")
});
action.setCallback(this,function(response){
var state=response.getState();
var responval=response.getReturnValue();
if(state==='SUCCESS')
{
component.set("v.acclist",responval);
}
else
{
alert('Error in processing the data');
}
});
$A.enqueueAction(action);
}
})
Application:
<aura:application extends="force:slds" >
<c:acccon></c:acccon>
</aura:application>
Q526. How do you delete records with a button in Lightning? Can you write the code?
Apex controller:
public class AccountDelController
{
@AuraEnabled
public static List<Account> displayAccounts()
{
List<Account> acclist=[select Id,Name from Account];
return acclist;
}
@AuraEnabled
public static List<Account> deleteAccRecord(String accId)
{
System.debug('AccountId'+accId);
Account acc=[select Id,Name from Account where Id=:accId];
delete acc;
return displayAccounts();
}
}
Component:
<aura:component controller="AccountDelController">
<aura:attribute name="acclist" type="list"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<table class="slds-table slds-table_cell-buffer slds-table_bordered">
<tr>
<td><b>Id</b></td>
<td><b>Name</b></td>
<td><b>Action</b></td>
</tr>
<aura:iteration items="{!v.acclist}" var="acc">
<tr>
<td>{!acc.Id}</td>
<td>{!acc.Name}</td>
<td>
<lightning:button label="Delete" value="{!acc.Id}" onclick="{!c.handleDelete}"/>
</td>
</tr>
</aura:iteration>
</table>
</aura:component>
JavaScript controller:
({
doInit : function(component, event, helper) {
var action=component.get("c.displayAccounts");
action.setCallback(this,function(response){
var state=response.getState();
var responsval=response.getReturnValue();
if(state==='SUCCESS')
{
component.set("v.acclist",responsval);
}
else
{
alert('unable to process the data');
}
});
$A.enqueueAction(action);
},
handleDelete:function(component,event,helper){
var currentRecordId=event.getSource().get("v.value");
//alert(currentRecordId);
var action=component.get("c.deleteAccRecord");
action.setParams({
accId:currentRecordId
});
action.setCallback(this,function(response){
component.set("v.acclist",response.getReturnValue());
});
$A.enqueueAction(action);
}
})
Application:
<aura:application extends="force:slds">
<c:AccountDeleteComponent/>
</aura:application>
Q527. Explain events in Lightning. Can you write a component event example?
A component event is used for child-to-parent communication (component composition).
Step 1: Create the event.
<!-- demoEvent -->
<aura:event type="COMPONENT">
<aura:attribute name="Info" type="String"/>
</aura:event>
Child component:
<aura:component>
<!-- This is the way we register the event in the component -->
<!-- You can give any name while registering the event, but the type should be the name of the event -->
<aura:registerEvent name="sampleDemo" type="c:demoEvent"/>
<lightning:button label="Submit" onclick="{!c.handleClick}"/>
</aura:component>
Child component controller:
({
handleClick:function(component,event,helper)
{
//getting the event properties
var comEvt=component.getEvent("sampleDemo");
//setting the value to the attribute
comEvt.setParams({
"Info":"Welcome to events"
//Info is the attribute name
//Welcome to events is the value of the attribute
});
//fire is used to fire the event.
//If you don't fire the event then it won't work
comEvt.fire();
}
})
Parent component:
<aura:component>
<c:childComponent/>
<aura:handler event="sampleDemo" type="c:demoEvent" action="{!c.handleEvent}"/>
</aura:component>
Parent component controller:
({
handleEvent:function(component,event,helper)
{
//getParam is used to get the value from the child component (event attribute)
var val=event.getParam("Info");
alert(val);
}
})
Application:
<aura:application>
<c:parentComponent/>
</aura:application>
Q528. How do you use an application event in Salesforce Lightning? Can you write the syntax?
var appEvent = $A.get("e.c:aeEvent");
Q529. What is a Lightning Component, and which programming models can be used to build one?
The Lightning Component framework is a user interface framework for developing single-page applications for desktop and mobile devices. It is possible to build Lightning components with two programming models: the original Aura Component model and the Lightning Web Component (LWC) model.
It supports partitioned multi-tier component development, using JavaScript for the client side and Apex for the server side.
Also noted:
Lightning components are modular features that can be added, moved or rearranged on Lightning pages - the Record Details, Chatter elements, Highlights Panel, Path display and so on. There are dozens of standard Lightning components, and you can also create your own custom components or get them from the AppExchange.
Q530. What is the difference between Lightning and Visualforce pages?
Visualforce (2008) is a page-centric framework designed for desktop applications; Lightning (2015) is a component-based UI framework designed with mobile first in mind and is used to build single page applications for desktop and mobile.
Lightning is device independent and responsive by default, because it subscribes to the Salesforce Lightning Design System (SLDS) styling out of the box.
Development is faster with Lightning because you assemble ready-made base components and reuse your own components, and nesting of components is possible.
In a Visualforce page JavaScript is optional and most work happens on the server; a Lightning component provides a client-side JavaScript controller in addition to the server-side Apex controller, so it makes far fewer server round-trips and caches on the client, which makes it faster.
Visualforce pages are still used in Classic and can be surfaced in Lightning; Lightning components can also be embedded in a Visualforce page using <apex:includeLightning/>.
Q531. How do you get the record Id from the URL in a Lightning component?
In an Aura component, implement the force:hasRecordId interface. It automatically adds an attribute <aura:attribute name="recordId" type="String"/> to the component (it is hidden by default), which the framework populates with the Id of the record the component is placed on.
<aura:component implements="force:hasRecordId,flexipage:availableForRecordHome">
<b>This is recordId {!v.recordId}</b>
</aura:component>
var recId = component.get("v.recordId");
force:hasRecordId only works on a record page, when the component is placed with the Lightning App Builder, and it works on a single record.
force:hasSObjectName adds an sObjectName attribute in the same way.
In a Visualforce page hosting a Lightning component you read the id with {!$CurrentPage.parameters.recId}.
In LWC the equivalent is @api recordId;.
Q532. What are the rendering lifecycle methods in an Aura component?
render()- called to render the component body and returns the DOM. You can override it after the framework fires the init event.afterRender()- runs after render() and lets you interact with the DOM once the rendering service has inserted the DOM elements.rerender()- called after an action changes data, so the component is updated with the new values rather than being rebuilt.unrender()- called when the component is destroyed, to clean up.Each of these has a super counterpart - superRender(), superAfterRender(), superRerender(), superUnrender() - which you must call when you override the method in an extending component.
The flow is: the framework fires the init event (so you can update the component or fire an event before rendering), then render(), then afterRender(). A browser event triggers Lightning events, whose actions update data; the rendering service tracks the stack of fired events, re-renders all components holding modified data, and fires the render event again so you can interact with the DOM tree.
Q533. How do you refresh one Lightning component when another component changes the data?
Handle the standard force:refreshView event in the component that must refresh, and point it at the method that reloads the data.
<aura:handler event="force:refreshView" action="{!c.doInit}" />
When any component (or the standard record page) fires force:refreshView, the handler runs doInit again and the component re-queries its data. In LWC, the equivalent for wired Apex data is to call refreshApex(this.wiredResult), or to use a Lightning message channel / getRecordNotifyChange so the other component can signal the change.
Visualforce & Classic
82 questions
Q534. What is Visualforce?
Visualforce is the component-based user interface framework for the Force.com platform. The framework includes a tag-based markup language similar to HTML. Each Visualforce tag corresponds to a coarse-grained or fine-grained user interface component, such as a section of a page or a field. Visualforce has about 100 built-in components, plus a mechanism whereby developers can create their own custom components.
Q535. What is the difference between a standard controller and a custom controller?
Standard controllers are generated automatically for all standard (and custom) objects. They provide all the functionality a standard page contains, such as editing or saving a record and the standard actions save, edit, delete, cancel and list.
Custom controllers are Apex classes written by a developer to override the standard functionality that a standard controller provides on a Visualforce page, implementing custom logic and data access. A controller extension adds functionality to a standard (or custom) controller without replacing it.
Also noted:
A standard controller inherits all the standard object properties, and the standard button functionality can be used directly.
A custom controller is an Apex class that defines custom functionality.
Q536. What is Visualforce, and how do you hide the header and sidebar in a Visualforce page?
Visualforce is a framework for the Force.com platform which enables developers to build custom interfaces hosted natively on the Lightning Platform. It uses a tag-based markup language like HTML, where each tag corresponds to a coarse- or fine-grained user interface component such as a page section, a related list or a field. It has about 100 built-in components, and developers can create their own.
To hide the header, set the showHeader attribute to false. To hide the sidebar, set the sidebar attribute to false. Both are Boolean attributes of the <apex:page> component:
<apex:page showHeader="false" sidebar="false">
<!-- page content -->
</apex:page>
Q537. How do you perform an AJAX request in Visualforce?
Use <apex:actionRegion> to mark the area of a Visualforce page that demarcates which components are processed by the Force.com server when an AJAX request is generated. Only the components within the body of <apex:actionRegion> are processed by the server. Related AJAX components include <apex:actionFunction>, <apex:actionSupport>, <apex:actionPoller> and the reRender attribute, which refreshes only part of the page.
Q538. How can we implement pagination in Visualforce?
Pagination in Salesforce refers to displaying a large number of records spread across multiple pages. The StandardSetController list control displays 20 records per page by default; pagination is implemented by using a controller extension and setting the page size.
public class MyExtension {
public ApexPages.StandardSetController setCon { get; set; }
public MyExtension(ApexPages.StandardSetController controller) {
setCon = controller;
setCon.setPageSize(10); // change records per page
}
}
The next(), previous(), first() and last() methods of StandardSetController drive the navigation, and getHasNext() / getHasPrevious() control the buttons.
Q539. How do you call a controller method from JavaScript on a Visualforce page?
To call a controller method (an Apex function) from JavaScript you use <apex:actionFunction>, which defines a new JavaScript function that calls the action:
<apex:actionFunction name="sayHello" action="{!sayHello}" rerender="out" status="myStatus"/>
Then call sayHello(); from JavaScript. (Alternatives are JavaScript Remoting with @RemoteAction and the AJAX toolkit.)
Q540. What are the types of bindings used in Salesforce (Visualforce)?
There are three types of bindings:
Data bindings - refer to the data set in the controller ({!accountName}).
Action bindings - refer to the action methods in the controller ({!save}).
Component bindings - refer to other Visualforce components (for example {!component.theId}).
Q541. Can you write getter and setter methods in Salesforce?
Yes.
A getter method returns values to the page from the controller. Every value calculated by a controller and displayed on a page must have a getter method (public String getName() { return name; }).
A setter method passes user-specified values from the page markup back to the controller. The setter method in a controller is executed automatically before any action methods.
In practice the shorthand automatic property public String name { get; set; } is used.
Q542. What is an attribute, and what is the reRender attribute tag?
The properties of a Visualforce component are called attributes. Every Visualforce component comes with attributes - for example <apex:commandLink> has value, action, id and so on.
The reRender attribute specifies a list of elements that are dynamically updated using Salesforce's AJAX library. There is no need for the entire page to refresh - only the portion of the page identified by the element ids named in the reRender attribute is redrawn.
Q543. Which tag is used to create a button, which tag is used for a URL link, and which tag is used for password protection in Visualforce?
The tag used for a button is <apex:commandButton>.
The tag used for a URL link is <apex:outputLink>.
The tag used for password protection (masked input) is <apex:inputSecret>.
Q544. What is the obligatory outer tag in Visualforce, and which tag is used to display a video?
The tag <apex:page> is the obligatory outer tag - every Visualforce page must be wrapped in it. The tag <apex:flash> is used to display a video (Flash content) in Visualforce.
Q545. How do you display a Chatter feed record on a Visualforce page?
Use the <chatter:feed> component. For example, to display the Chatter feed for the currently logged-in user:
<apex:page>
<chatter:feed entityId="{!$User.Id}"/>
</apex:page>
Q546. How is a link passed in Visualforce?
A link is passed in Visualforce through a hyperlink - the <apex:outputLink> component (which renders an HTML anchor tag) or <apex:commandLink> when the link must call a controller action.
Q547. What is the purpose of apex:outputLink?
<apex:outputLink> links to a URL. The body of <apex:outputLink> contains the image or text that is displayed as the link, and it renders as an HTML <a> anchor tag. Unlike <apex:commandLink>, it does not invoke a controller action.
Q548. Which tag is used for calling a controller name in Visualforce?
The controller is referenced through the controller attribute of the <apex:page> tag - for example <apex:page controller="MyController">. (For a standard controller you use standardController, and for extensions the extensions attribute.)
Q549. Can we reference a standard controller and a custom controller attribute at the same time on a Visualforce page?
No. You cannot reference both the standardController and the controller attributes on the same <apex:page> tag. To combine standard behaviour with custom logic, use the standardController attribute together with the extensions attribute, which points to a controller extension class.
Q550. What is development mode in Visualforce, when do we enable it, and how?
Development mode is the best way to build Visualforce pages, because it lets you view the code and the output simultaneously in a footer editor. Enable it from your personal settings: Setup > My Personal Information / Advanced User Details > edit the user and select "Development Mode" (and optionally "Show View State in Development Mode").
Development mode helps by:
Letting you define new Visualforce pages simply by entering a new URL.
Showing error messages with detailed stack traces beyond what standard users receive.
Displaying a footer with the page's view state, a link to the component reference documentation and a link to any associated controller.
Offering a page markup editor with highlighting, find-and-replace and auto-suggest for component tags and attribute names.
Q551. What is a custom Visualforce component?
Custom components are user-defined components that can be reused several times in one or more Visualforce pages. They are defined with <apex:component>, can declare <apex:attribute> parameters and have their own controller, and are used on a page with the <c:MyComponent> tag.
Q552. Explain the apex:outputText, apex:outputLabel and apex:outputLink tags in Visualforce.
<apex:outputText value="sample Output value"></apex:outputText>
<apex:outputLabel value="sample Output value"></apex:outputLabel>
<apex:outputLink value="www.google.com">Google</apex:outputLink>
<apex:outputText> displays text, used like a heading or a plain value.
<apex:outputLabel> displays a label, also used like a heading, and can be associated with an input using the for attribute.
<apex:outputLink> behaves like an HTML <a> anchor tag - it links to the URL in value and displays its body as the link text.
Q553. What are the apex:panelBar and apex:panelBarItem tags in Salesforce?
<apex:panelBar> creates a collapsible accordion-style panel, and each <apex:panelBarItem> is one expandable item within it. Up to 1000 items can be inserted.
<apex:panelBar>
<apex:panelBarItem label="Item 1">item1 content</apex:panelBarItem>
<apex:panelBarItem label="Item 2">item2 content</apex:panelBarItem>
</apex:panelBar>
Q554. Give an example of the apex:panelGrid tag.
<apex:panelGrid> renders the enclosed components in an HTML table, filling the given number of columns row by row.
<apex:panelGrid columns="4">
<apex:outputText value="first cell" />
<apex:outputText value="second cell" />
<apex:outputText value="third cell" />
<apex:outputText value="fourth cell" />
</apex:panelGrid>
Q555. Give an example of the tabPanel tag in Salesforce.
<apex:tabPanel switchType="client" selectedTab="name2" id="theTabPanel">
<apex:tab label="One" name="name1" id="tabOne"> Tab1 </apex:tab>
<apex:tab label="Two" name="name2" id="tabTwo"> Tab2 </apex:tab>
</apex:tabPanel>
switchType controls how tabs switch - client (all content sent to the browser), server (a full page request per tab) or ajax (a partial page request).
Q556. What is the apex:toolbar tag in Visualforce used for?
It is used to show short links in a toolbar - a styled horizontal bar of links, buttons and other components at the top or bottom of a page.
<apex:toolbar id="theToolbar">
<apex:outputLink value="google.com">google</apex:outputLink>
</apex:toolbar>
Q557. How do you replace a standard page with a custom Visualforce page?
Go to Custom Object > Buttons, Links and Actions and override the standard action (View, New, Edit, Tab, List) with your Visualforce page. You can also create a custom button that points at the Visualforce page and add it to the page layout. For the override to be available the Visualforce page must use the standard controller for that object.
Q558. Can you use more than one controller extension on a Visualforce page, and how?
List them in the extensions attribute separated by commas:
<apex:page standardController="Contact" extensions="TestClass1, TestClass2">
</apex:page>
If both extensions define a method with the same name, the method in the first extension listed takes precedence when resolving the reference.
Q559. What Date, Time and String functions are available in Visualforce?
Answer supplied - source left blank.
Visualforce expressions support the same library of predefined formula functions available in Apex and Aura formulas. Common examples include:
Date/Time: TODAY(), NOW(), DATEVALUE(), DAY(), MONTH(), YEAR(), ADDMONTHS(), DATETIMEVALUE()
String: LEN(), LEFT(), RIGHT(), MID(), TRIM(), LOWER(), UPPER(), SUBSTITUTE(), CONTAINS(), BEGINS(), TEXT(), VALUE(), FIND(), HYPERLINK()
Logical: IF(), AND(), OR(), NOT(), ISBLANK(), ISNULL(), CASE()
They are used inside merge-field expressions, for example {!TEXT(TODAY())} or {!UPPER(Account.Name)}.
Q560. How do you render a Visualforce page as a PDF document?
Use the renderAs attribute on <apex:page>:
<apex:page standardController="Account" renderAs="pdf">
Note that when rendering as PDF the page cannot use <apex:form> input components or JavaScript-driven rendering, and only a subset of CSS is supported.
Q561. What kind of web content can be added to Visualforce?
HTML, CSS, JavaScript and Java-based content (applets/Flash) can be added, along with images and archives uploaded as static resources, and content embedded via iframes.
Q562. How do you upload CSS as a static resource and add it to a Visualforce page?
Upload the stylesheet (or a zip archive containing it) as a static resource in Setup, then reference it:
<apex:stylesheet value="{!URLFOR($Resource.style_resources, 'styles.css')}"/>
For a single (non-archive) resource, <apex:stylesheet value="{!$Resource.myStyles}"/> is enough.
Q563. How do you add a Visualforce page to a page layout?
The page must use the standard controller for that object:
<apex:page standardController="MyObject__c">
Then, in the page layout editor, the Visualforce Pages category becomes available in the palette and the page can be dragged onto a section of the layout, where its height, width and scrollbars can be set.
Q564. How do you add a Visualforce page to a mobile menu item?
Using <apex:canvasApp> we can achieve this - the Visualforce page is exposed through a canvas app which can then be added to the mobile navigation menu. (A Visualforce page can also be surfaced in the mobile navigation menu by creating a Visualforce tab for it and adding that tab to the mobile navigation.)
Q565. What is view state in Visualforce?
Asked at: Appcino
View state holds the state of a Visualforce page - the values of the class-level instance variables of the controller - and carries it from one transaction (request) to the next.
It is stored in a hidden form field, so it only exists inside an <apex:form> tag.
You can inspect it with the View State tab in the Developer Console once Development Mode is enabled for your user.
Keep it small: mark variables transient when they do not need to survive the postback.
Q566. What is the maximum view state size in Visualforce?
Asked at: Appcino
170 KB. If the view state exceeds 170 KB the page throws a Maximum view state size limit exceeded error, so large collections should be marked transient or re-queried instead of stored.
Q567. What is an action region in Visualforce?
Asked at: Appcino
<apex:actionRegion> marks the area of a Visualforce page whose components are processed by the server when an AJAX request is generated - only the components inside its body are sent and validated.
It gives you a partial update of blocks of the page.
It always works together with the
reRenderattribute, which names the components to redraw.
Q568. In a PageReference, what is the difference between setRedirect(true) and setRedirect(false)?
Asked at: Cloud 360
Answer supplied - source left blank.
PageReference.setRedirect() controls whether the browser performs a client-side redirect or the page is served in the same server-side request.
setRedirect(true)- an HTTP GET redirect is issued. A new request begins, so the view state and controller state are lost, and the URL in the address bar changes. Use it when you must go to a different page/controller cleanly (a "redirect after post").setRedirect(false)(the default) - the navigation happens within the same request; the view state is preserved, and the controller's state (and therefore the current data) is carried over. The URL does not change.Note: if the target page uses a different controller, Salesforce forces a redirect regardless of the setting.
Q569. If a Visualforce page has multiple extensions with methods of the same name, which method is called?
Asked at: Cloud 360
When a page uses a standard controller plus extensions, the later extension overrides the earlier one - the first controller's method is overridden by the second, so the second controller's method is executed. Methods are resolved left to right in the extensions attribute, and the first occurrence found (last one listed that defines the method) wins.
Also noted:
Only one controller can be assigned to a page via the controller attribute, so the second declaration overrides the first and the second controller's method is used. Alternatively, define distinct controller names and call them explicitly.
Q570. How do you use a controller in a Visualforce page?
There are two types of controller: a standard controller (auto-generated by Salesforce for an object) and a custom controller (user-defined Apex class). They are declared on the <apex:page> tag using the standardController or controller attribute, and additional logic can be layered on with the extensions attribute.
Q571. How is an Apex class used within a Visualforce page?
1. When you want to call an Apex class in a Visualforce page you have to declare it in the following format:
<apex:page controller="class name">
Whenever we call a Visualforce page in which the controller attribute is defined, it will first create an object for the Apex class that is defined in the controller.
2. When the object is created for the Apex class, it first invokes the constructor.
Q572. What is JavaScript remoting for Apex controllers?
Use JavaScript remoting in Visualforce to call methods in Apex controllers from JavaScript.
JavaScript remoting has 3 parts:
1. The remote method invocation you add to the Visualforce page, written in JavaScript.
2. The remote method definition in your Apex controller class. This method definition is written in Apex, but there are a few differences from normal action methods.
3. The response handler callback function you add to, or include in, your Visualforce page, written in JavaScript.
Q573. How do you add JavaScript remoting to a Visualforce page?
To use JavaScript remoting in a Visualforce page, add the request as a JavaScript invocation with the following form:
[namespace.]controller.method(
[parameters...,]
callbackFunction,
[configuration]
);
namespace is the namespace of the controller class.
controller is the name of your Apex controller.
method is the name of the Apex controller method you are calling.
parameters is the comma-separated list of parameters that your method takes.
callbackFunction is the name of the JavaScript function that will handle the response from the controller.
configuration configures the handling of the remote call and response.
Q574. What is the main difference between using the dataTable tag and the pageBlockTable tag?
pageBlockTable: renders in the default Salesforce standard format.
dataTable: used to design custom formats.
Q575. Which tag is used with both radio buttons and picklists to create the selectable values?
The <apex:selectOptions> tag (used together with <apex:selectOption>) is used with both radio buttons and picklists to create the selectable values.
Q576. What are some Apex classes that are commonly used within a controller?
StandardController, SelectOption, PageReference, Message, and so on.
Q577. What are the effects of using the transient keyword?
The transient keyword prevents the data from being saved into view state. This should be used for very temporary variables.
Q578. How do you configure JavaScript remoting requests?
Configure a remoting request by providing an object with configuration settings when you declare the remoting request. JavaScript remoting supports the following configuration parameters:
Name Data type Description
--- --- ---
buffer Boolean Whether to group requests executed close to each other in time into a single request. The default is true.
escape Boolean Whether to escape the Apex method's response. The default is true.
timeout Integer The timeout for the request in milliseconds. The default is 30000 (30 seconds).
Q579. What is an S-Control?
S-Controls are the predominant salesforce.com widgets which are completely based on JavaScript. These are hosted by Salesforce but executed at the client side. S-Controls are superseded by Visualforce now.
Q580. Does Visualforce still support the usage of merge fields like S-Controls?
Yes. Just like S-Controls, Visualforce pages support embedded merge fields.
Q581. What is a static resource?
A static resource is a place where you can upload the supporting files that can be referenced in a Visualforce page or Lightning component - archives (.zip, .jar), images, style sheets, JavaScript and other files. They are referenced with $Resource / URLFOR(), and the Lightning platform acts as a CDN for them. The maximum size is 5 MB per resource and 250 MB per org.
Q582. How do you call JavaScript using a static resource in a Visualforce page?
Add the JavaScript file to Static Resources: Setup -> Develop -> Static Resources -> click on 'New' -> enter Name: filename, add the file from your local desktop and save.
You can then reference that file in the Visualforce page using the $Resource global variable with <apex:includeScript>.
Q583. How do you use the transient keyword to store a password in a hierarchy custom setting?
Because your myPref property is transient, the initialisation you perform in the constructor won't round trip when the page posts back.
When using transient and a protected custom setting, use separate properties that are transient and then only work with the custom setting in the post back method.
Controller:
public with sharing class TestCustomSettings {
// transient to ensure they are not transmitted as part of the view state
public transient String password1 {get; set;}
public transient String password2 {get; set;}
public PageReference save() {
// Use getInstance() rather than getValues()
TestR__c myPref = TestR__c.getInstance(UserInfo.getOrganizationId());
if (myPref == null) {
myPref = new TestR__c();
myPref.SetupOwnerId = UserInfo.getOrganizationId();
}
myPref.Password1__c = password1;
myPref.Password2__c = password2;
// By using upsert you don't need to check if the Id has been set.
upsert myPref;
}
}
Visualforce page: use <apex:inputSecret> rather than <apex:inputField> so that the browser will mask the input.
Q584. What is the maximum size of a PDF generated using the Visualforce renderAs attribute?
15 MB.
Q585. How many controllers can be used in a Visualforce page?
Salesforce comes under SaaS, so we can use one controller and as many extension controllers as needed.
Q586. What is the difference between actionSupport and actionFunction?
actionFunction: invokes the controller method from JavaScript using AJAX, and we can use actionFunction from different places on the Visualforce page.
actionSupport: invokes the controller method using AJAX when an event occurs on the page such as onMouseOver, onClick, etc., and we can use actionSupport for one particular single Apex component.
Q587. How many field dependencies can we use in a Visualforce page?
Maximum we can use 10 field dependencies in a Visualforce page.
Q588. What are the main Visualforce input tags and what do they do?
The input components render editable form fields and must sit inside an <apex:form>:
<apex:inputField>/<apex:input>- a generic input bound to a controller value, rendering the field's type-appropriate widget:
<apex:input value="{!inputValue}" id="theTextInput"/>
<apex:inputText>- a single-line free-text box (an HTML <input type="text">).<apex:inputSecret>- a masked input used for passwords.<apex:inputTextarea>- a multi-line text area; supports a rich-text editor.<apex:inputCheckbox>- a checkbox for Boolean values.<apex:inputFile>- a file upload control (returns a Blob plus the file name and content type).<apex:inputHidden>- a hidden field, not shown to the user but posted back with the form.
Q589. What are the main Visualforce output tags and what do they do?
The output components display read-only data:
<apex:outputField>- displays a field's value with the standard Salesforce formatting, respecting field-level security and the field type (dates, currency, lookups become links).<apex:outputText>- displays arbitrary text or a formatted value.<apex:outputLabel>- a label for an input field, tied to it with the for attribute (acts like a heading for the field).<apex:outputLink>- renders an HTML <a> anchor tag linking to a URL; the body is the text or image shown.<apex:outputPanel>- a container (<span> or <div> depending on layout) used mainly as a target for reRender.
Q590. What are the main Visualforce select tags and what do they do?
The select components render multiple-choice controls, populated by <apex:selectOption> or <apex:selectOptions>:
<apex:selectCheckboxes>- a set of related checkboxes from which multiple values can be selected.<apex:selectList>- a drop-down list or multi-select list box; size="1" makes it a picklist.<apex:selectOption>- defines a single possible value inside a select component.<apex:selectRadio>- a set of radio buttons from which exactly one value can be selected.
Two related utility tags often listed with them:
<apex:variable>- declares a local variable that can be used within the page markup.<apex:vote>- displays the voting/rating widget for a record that supports voting.
Q591. What are the main Visualforce page tags and what do they do?
<apex:page>- the basic, obligatory outer tag; there can be only one per page.<apex:pageBlock>- a styled area into which multiple sections can be inserted.<apex:pageBlockSection>- a section (with a heading and columns) inside a page block.<apex:pageBlockSectionItem>- inserts a row (a label/field pair) within a section.<apex:pageMessage>- shows a message such as a success or an error. Attributes:severitywith the values confirm, info, warning, error, andstrength(0 to 3) which controls the icon image.<apex:pageBlockTable>- renders a styled table of records inside a page block.<apex:pageBlockButtons>- provides the button bar area within a page block.<apex:commandButton>- a button placed inside <apex:pageBlockButtons>; key attributes are value (for example "Save", "Cancel", "Close") and action.
There are also action tags and style tags. The title attribute is used to give a heading to a page block or a section.
Q592. Show programs using a custom controller, a standard controller, a controller extension and a standard list controller.
Custom controller
<apex:page controller="InsertClass" tabStyle="International_OP_Patient_Journey__c" showHeader="false">
<apex:form>
<apex:pageBlock>
<apex:pageBlockSection>
<apex:inputField value="{!op.name}"/>
</apex:pageBlockSection>
</apex:pageBlock>
<apex:pageBlockButtons>
<apex:commandButton value="Save" action="{!insertMe}" />
</apex:pageBlockButtons>
</apex:form>
</apex:page>
public class InsertClass {
public Account acc { get; set; }
public InsertClass() {
acc = new Account();
}
public void insertMe() {
insert acc;
acc = new Account();
}
}
Standard controller
<apex:page standardController="Account">
<apex:form>
<apex:pageBlock>
<apex:pageBlockSection>
<apex:inputField value="{!Account.name}"/>
</apex:pageBlockSection>
<apex:pageBlockButtons>
<apex:commandButton value="Save" action="{!save}" />
<apex:commandButton value="Edit" action="{!edit}" />
<apex:commandButton value="Delete" action="{!delete}" />
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>
Standard list controller
<apex:page standardController="Account" recordSetVar="accounts">
<apex:repeat value="{!accounts}" var="a">
<apex:outputLink value="{!a.Name}"></apex:outputLink>
</apex:repeat>
</apex:page>
Controller extension
<apex:page standardController="Account" extensions="e1">
{!hello}
<apex:pageBlock>
<apex:pageBlockSection>
<apex:detail relatedList="false" />
<apex:relatedList list="Opportunities"/>
<apex:relatedList list="Contacts"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>
public class e1 {
public e1(ApexPages.StandardController con) {}
public String hello = 'How are you';
public String getHello() {
return hello;
}
}
Q593. What are the standard list controller actions in Visualforce?
<apex:commandButton>- creates a button that calls an action:
<apex:commandButton action="{!save}" value="Save" id="theButton"/>
<apex:commandLink>- creates a link that calls an action:
<apex:commandLink action="{!save}" value="Save" id="theCommandLink"/>
<apex:actionPoller>- periodically calls an action:
<apex:actionPoller action="{!incrementCounter}" reRender="counter" interval="15"/>
<apex:actionSupport>- makes an event (such as onclick or onmouseover) on another, named component call an action:
<apex:actionSupport event="onclick" action="{!incrementCounter}" rerender="counter" status="counterStatus"/>
<apex:actionFunction>- defines a new JavaScript function that calls an action:
<apex:actionFunction name="sayHello" action="{!sayHello}" rerender="out" status="myStatus"/>
<apex:page action="...">- calls an action when the page is loaded.
Q594. How can you override a list button with a Visualforce page?
The Visualforce page must be a list controller page, i.e. it must have the recordSetVar attribute defined in the <apex:page> tag.
Q595. How can you call a Visualforce page from a controller method?
Use a PageReference object and return it from the controller method to navigate to a Visualforce page.
Q596. How can you refresh a particular section of a Visualforce page?
This is done using the reRender attribute on an AJAX action component (for example <apex:commandButton reRender="panelId"/>), pointing to the ID of the component to refresh.
Q597. How can you use a custom label in a Visualforce page?
Use the $Label global variable.
{!$Label.SampleLabel}
Q598. What is actionPoller in Visualforce?
<apex:actionPoller> sends an AJAX request to the server at a specified time interval.
Q599. How do we access a static resource in Visualforce?
Use the $Resource global variable.
{!$Resource.TestResourceName}
Q600. How do you embed a Visual Flow in a Visualforce page?
Use the flow interview component.
<flow:interview name="MyFlowName"/>
Q601. How do you enable inline editing on a Visualforce page?
You can enable inline editing on a Visualforce page by using the <apex:inlineEditSupport> component inside the component you want to make editable.
Q602. Can you use a DML statement in a Visualforce component controller?
To perform DML from a Visualforce component's controller you must declare allowDML="true" on the <apex:component> tag; otherwise you get the exception "DML is currently not allowed".
Q603. How can you display the status of an AJAX update request on a Visualforce page?
Use the <apex:actionStatus> component to display the status of an AJAX request.
Q604. How can you make fields required on a Visualforce page?
Set required="true" on the input component.
<apex:inputField value="{!account.Description}" required="true"/>
Q605. How can you implement custom functionality for a Visualforce page that uses a standard controller?
Associate an Apex controller class with the standard controller using the extensions attribute on the <apex:page> tag.
Q606. How can you get the current record ID in a Visualforce page?
Use the following in the controller:
ApexPages.currentPage().getParameters().get('id');
Q607. How can you deliver a Visualforce page in Excel form?
Set the content type on the page tag.
<apex:page contentType="application/vnd.ms-excel#Contacts.xls">
Q608. How can you create an input field for a date on a Visualforce page?
Use <apex:inputField> bound to an existing Date field on an object; the platform then renders the date picker automatically.
Q609. How can you place an entire Visualforce page inside another Visualforce page?
Use the <apex:include> component.
<apex:include pageName="OtherPage"/>
Q610. How can view state errors in a Visualforce page be avoided?
Use the transient keyword on variables wherever possible.
Clear unused collections.
Use only one <apex:form> tag on a Visualforce page.
Q611. What are custom controllers?
A custom controller is an Apex class that implements all the logic for a Visualforce page without leveraging a standard controller.
Q612. Can a custom controller class accept arguments?
No. A custom controller cannot accept any arguments; it must use a no-argument constructor for the outer class.
Q613. What types of methods can be defined for Visualforce controllers?
Getter methods
Setter methods
Action methods
Q614. What are the types of controllers available in Visualforce?
1. Standard controller
Gives you the standard functionality (view, save, edit, delete, cancel) that Salesforce provides for an object.
<apex:page standardController="Contact"></apex:page>
2. Custom controller
An Apex class that provides functionality not offered by the standard controller. Properties need getter and setter methods, and the constructor takes no parameters.
<apex:page controller="MyController"></apex:page>
3. Controller extension
Lets you use the functionality of more than one controller on a page: a standard controller with a custom controller, a custom controller with another custom controller, or a standard list controller with a custom controller.
<apex:page standardController="Contact" extensions="TestClass1, TestClass2"></apex:page>
4. Standard list controller (standard set controller)
Used to work with a record set (multiple records) and gives you list views, filtering and pagination. It needs the recordSetVar attribute.
<apex:page standardController="Contact" recordSetVar="contacts"></apex:page>
In Apex the equivalent is ApexPages.StandardSetController. The default page size is 20 records.
Q615. What are the Visualforce action components used for AJAX behaviour?
These components are used to perform partial (AJAX) requests such as refreshing only part of a page:
<apex:actionPoller> - calls an action repeatedly at a specific interval of time (the interval attribute is in seconds).
<apex:actionFunction> - lets you call an Apex controller method from JavaScript code.
<apex:actionSupport> - performs an action in support of another element when a particular event occurs on it, for example onchange of a picklist.
<apex:actionRegion> - defines the region of the page that is processed by the server, allowing a partial update of blocks of the page. It always works with the reRender attribute.
<apex:actionStatus> - shows the progress of the request; use <facet name="start"> and <facet name="stop"> to show a spinner image while the request is running.
The controller methods behind them fall into three kinds:
Action methods - perform an operation such as insert, update, delete or upsert; used by <apex:commandButton>, <apex:commandLink>, actionPoller, actionFunction and actionSupport.
Getter methods - get values from the database and return them to the page (identified by the get keyword or a property).
Navigation methods - navigate from one page to another using an instance of the PageReference class, for example PageReference pr = new PageReference('/' + ac.Id);.
Admin, Configuration & Automation
157 questions
Q616. What is the use of custom settings and custom metadata types, and why do we use them?
Custom Settings store application configuration data such as settings and defaults, and let you retrieve that data at the organization, profile or user level. They are cached in the application cache, so access does not cost a SOQL query when using the provided methods, and they are accessible from Apex code and formula fields. There are two types - List and Hierarchy.
List<MyListCustomSetting__c> customSettingsList =
[SELECT Id, Name, Field1__c, Field2__c FROM MyListCustomSetting__c];
Custom Metadata Types hold metadata - data that describes other data. For example, in a Salesforce org there is a standard object called Account; when you add a record with a customer's contact information to an Account you are adding both metadata and data. Field names such as First Name and Last Name are metadata. Custom metadata records are deployable between orgs (they travel with change sets/packages), so they are ideal for configuration that must move with the code.
List<MyCustomMetadataType__mdt> metadataRecords =
[SELECT Id, MasterLabel, Field1__c, Field2__c FROM MyCustomMetadataType__mdt];
Why use them: to avoid hardcoding values in Apex, to let admins change behaviour without a deployment, and (for custom metadata) to migrate configuration along with the code.
Also noted:
Custom settings are similar to custom objects. Developers create custom sets of data and associate that data with an organization, a profile or a specific user. Exposing custom setting data to the application cache is beneficial because it gives efficient access without the cost of repeated queries to the database. The data can be used by the SOAP API, validation rules and formula fields.
Hierarchy type - values can be set at the org, profile and user level, with the most specific value winning.
List type - a simple, org-wide set of reusable static data rows.
Q617. What is a bucket field in reports, and how is it used?
Bucket fields are used in Salesforce reports to group together field values into categories. You define a bucket field on a report column and assign values into named buckets - for example grouping many industry picklist values into "Manufacturing", "Retail" and "Other". These fields are not created on the Salesforce platform as real fields; they only exist inside the report itself. Bucketing supports picklist, number and text field types.
Also noted:
Bucketing lets you quickly categorise report records without having to create a formula or a custom field. The bucket field exists only inside the report and groups field values into named buckets (for example grouping Amount into Small/Medium/Large).
Q618. What are the differences between workflow and Process Builder, and between a trigger and Process Builder?
Workflow vs Process Builder
Both are declarative automation tools that extend the Salesforce platform's functionality and automate business processes.
Workflows can only handle four actions: email alerts, outbound messages, task creation and field updates.
Process Builder has a much larger set of functions: creating a record, posting to Chatter, launching a flow, submitting for approval, quick actions, calling Apex and updating related records.
If a process previously needed different workflows for different outcomes, the same can now be accomplished with one process.
A workflow evaluates only single criteria before triggering the automation; Process Builder can evaluate multiple criteria and trigger different automation depending on which criterion is met.
Trigger vs Process Builder
A trigger is Apex code, so it can do anything - complex logic, querying, before context field changes without extra DML, deletes, callouts (asynchronously), and cross-object logic in any direction.
Process Builder is declarative and runs after the record is saved, so it always causes an extra save/DML, cannot handle delete events, and cannot query arbitrary data.
Use Process Builder for simple, admin-maintainable automation; use a trigger for bulk-safe, complex or performance-sensitive logic.
Also noted:
Process Builder is an automated process similar to workflow rules, but it gives extra options such as calling an Apex class, sending custom notifications, submitting a record to an approval process, creating records and updating related records.
It is a graphical representation of the process, so the whole flow is visible in one canvas.
Like a workflow rule it consists of criteria and actions, and the actions can be immediate or scheduled.
A single process can contain many criteria nodes, whereas a workflow rule has only one criterion per rule.
Setup > Process Builder. Scheduled actions can be monitored under Monitoring > Time-Based Workflow.
Q619. What is the difference between ISNULL and ISBLANK?
Use the ISBLANK() function for text fields. Text fields can never be NULL - even if nothing is provided as a value they are an empty string - so ISNULL() on a text field always returns false. ISNULL() only detects a genuinely empty (null) value, which applies to number, date and other non-text field types.
ISBLANK() works for any field type and is the recommended function; ISNULL() is retained for backwards compatibility.
Q620. What is the limit of Data.com records that can be added to Salesforce?
In the Data.com Users section, find your name to view your monthly limit - it shows how many records have already been added or exported for the month. Navigate to Setup, enter Users in the Quick Find box and select Prospector Users. The limit is set per user by the administrator from the org's purchased record allocation.
(Note: Data.com Prospector and Data.com Clean were retired on 31 July 2021. In a current interview, mention the successors instead - Data Cloud, Lightning Data on AppExchange, or third-party enrichment such as ZoomInfo or Dun & Bradstreet.)
Q621. What is an Audit Trail in Salesforce?
Administrators need to make changes in the organisational setup. The Setup Audit Trail history helps you track the recent 20 changes made in Setup by multiple administrators (displayed on screen), and the last 6 months of changes are kept and can be downloaded as a CSV file. It records the date, the user and the change that was made.
Q622. What is a custom label in Salesforce? How many custom labels can you define and of what size?
Custom labels enable developers to create multi-lingual applications - they automatically present information or messages in the user's native language. They are custom text values that are accessible from Apex classes, Lightning components and Visualforce pages ($Label.MyLabel).
You can create up to 5,000 custom labels for each organisation, and each label can be up to 1,000 characters in size.
Q623. What is the user interface in Salesforce?
The user interface settings in Salesforce let you configure the experience your users get. From Setup > User Interface you can enable and disable settings such as collapsible sections, hover details, inline editing, related list hover links and the Salesforce Notification Banner, so the org is tailored to give the best working experience for your users.
Q624. Name a few global variables which are used in formula fields and validation rules.
$User - fields of the running user.
$Profile - fields of the running user's profile.
$Label - custom labels.
$Record (in flows) / $RecordType - the record and its record type.
$Organization, $Setup (custom settings), $Permission, $UserRole, $System.OriginDateTime, $Api, $Action, $ObjectType.
Q625. What are the differences between object-specific actions and global actions?
Both types can create records, but only object-specific actions can update records (and log a call, send email, or launch a custom action in the record's context).
Object-specific create actions create records that are automatically associated with the current record, because the action has a defined relationship to it. A record created by a global create action has no relationship with any other record.
Global actions are added to global publisher layouts and can appear anywhere (Home, Chatter feed, record pages); object-specific actions appear only on that object's page layouts.
Q626. How do you pass the current record Id to a screen flow, and is it possible to send the entire record?
To pass the current record Id, declare a variable named recordId of type Text and select the option Available for input. When the flow is placed on a Lightning record page, the record Id is passed in automatically.
To pass the entire record, create a variable (for example recordId or record) of type Record, choose the object type as that particular sObject, and mark it Available for input.
Q627. Is it possible to use a formula field in a roll-up summary calculation if the formula refers to another object?
No. A roll-up summary cannot aggregate a formula field that references fields on another object (cross-object formulas), and it cannot roll up formulas that include certain functions. To get the value, you need automation (flow, Apex or process) that copies the calculated value into a plain numeric field on the child, and then roll up that field.
Q628. What is the consideration while deleting an approval process?
Approval processes can be deactivated and deleted, but an approval process that still has records in pending status can only be deactivated, not deleted. To delete an approval process, ensure that there are no records in the org locked in that approval process (approve, reject or recall the pending items first); otherwise an error is raised.
Q629. What happens during lead merging?
You can select up to 3 leads to merge. They are identified as duplicates based on the duplicate rules configured in the org. One lead is chosen as the master record, and the read-only and hidden field values are retained from that master. After the merge, the result is a single lead record and the other two records are deleted.
Q630. How do you convert a 15-digit record Id to an 18-digit Id in a formula or validation rule?
Use the CASESAFEID() function - for example CASESAFEID(Id) - which returns the 18-character, case-safe version of the 15-character Id.
Q631. Is it possible to hard delete records using Data Loader?
Yes. Enable the system permission Bulk API Hard Delete for the user, and select the Bulk API option in the Data Loader settings before performing the deletion. Hard-deleted records bypass the Recycle Bin and cannot be recovered.
Q632. Is it possible to show validation errors in a screen flow?
Yes. Certain screen components support the Validate Input option, where you supply a formula and an error message. Note that the semantics are the inverse of standard validation rules: the condition provided must evaluate to false for the error to appear (the formula describes what a valid entry looks like), which is the opposite of standard/object validation rules where a true condition raises the error.
Q633. How can we enable email approval response, and what are a few response keywords that will approve or reject the request?
From Setup > Process Automation Settings, select Enable Email Approval Response. The approver can then reply to the approval request email with a keyword in the first line of the reply body. Accepted keywords include: Approve, Approved, Yes for approval, and Reject, Rejected, No for rejection. Comments can be added on the second line.
Q634. What is an app in Salesforce (admin perspective)?
A Salesforce app is a group of tabs (and, in Lightning, navigation items and utility bar items) that makes it easy for users to access a set of related features in the Salesforce browser app or mobile app.
Q635. What are page layouts and record types in Salesforce?
Page layouts organize the UI of a record page - which fields, related lists, buttons and sections appear and in what order - and are assigned based on the user's profile (and record type).
Record types allow you to associate different business processes with a record and to define different sets of picklist values, page layouts and processes for different profiles or user groups on the same object.
Q636. What are the different data management tools in Salesforce?
Data Import Wizard - a browser-based tool for importing up to 50,000 records.
Data Loader - a client application for inserting, updating, upserting, deleting, hard deleting, exporting and exporting-all up to 5 million records.
Data Export (weekly/monthly scheduled backup), plus third-party ETL tools such as Jitterbit, Informatica, MuleSoft and dataloader.io.
Q637. What is the Data Import Wizard, and how does it compare with Data Loader?
Data import and export means importing and exporting data to and from Salesforce. Only .csv files are supported for bulk import and export.
Data Import Wizard (Setup > Data Import Wizard):
Use when records are fewer than 50,000.
It is an internal (browser-based) tool.
Supports some standard objects - leads, contacts, accounts, campaign members and solutions - and all custom objects.
Can only be used for importing data.
Cannot save field mappings for future use.
Duplicate records are checked on the basis of name, email Id or Salesforce Id.
Offers only insert, update and upsert.
Data Loader (Setup > Integrations > Data Loader):
Use when the record volume is more than 50,000 and up to 5 million records.
It is an external, installed tool (requires Java/JDK).
Can be used for all standard and custom objects.
Can be used for both import and export.
Mappings can be saved for future use.
Records are matched on the basis of Salesforce Id (or an External Id for upsert), which means it can duplicate data if you match only on Id.
Offers delete (and hard delete) in addition to insert, update and upsert.
Supports a directory path for the success and error result files, and a command-line interface for scheduling.
Data Export (Setup > Data Export): used to export selected objects or all data for backup, in .csv format. A scheduled export can be set up with at least a 48-hour (weekly/monthly) interval.
Data Loader operations:
Insert - log in and supply the .csv file to insert.
Update - matches on Salesforce Id (the record Id from the URL); update in Data Loader is only done on the basis of Salesforce Id.
Export - choose which fields to export and the path to export to, with the option to build a query and add conditions. Export does not return deleted records.
Export All - exports all records of the object including those in the Recycle Bin. A SELECT * query is not supported; fields must be listed explicitly.
External Id - used to remove duplicates during insert/upsert. When creating the field, tick "Set this field as the unique record identifier from an external system" to make it usable as an External Id.
Q638. In Data Loader, what is the difference between Export and Export All?
Asked at: Cloud 360
Answer supplied - source left blank.
Export exports all the records of a particular object to a .csv file, excluding records that are in the Recycle Bin (soft-deleted records).
Export All exports all records for that object including the deleted records that are still in the Recycle Bin (and archived activities).
Both let you choose the fields and add a filter condition; SELECT * is not supported, so the fields must be selected explicitly.
Q639. What is a formula field in Salesforce?
A formula field is a read-only field used to display a calculated value:
1. It is used to create a formula and is read-only.
2. It shows some calculation or comparison based on the object's data.
3. It can make use of functions to calculate values.
4. It is always associated with a return type (Text, Number, Currency, Date, Checkbox, Percent).
Formula fields are recalculated whenever the record is viewed, and are not stored in the database.
Q640. What is a cross-object formula field?
A cross-object formula field displays a value from one object's record on another related object by referencing merge fields on those objects. It works with lookup as well as master-detail relationships, and can span up to 10 relationships (spanning up to 5 unique objects) going up from child to parent.
Q641. What are reports in Salesforce?
A report is a set of records displayed in the form of rows and columns. Report data can be filtered, grouped and displayed graphically as a chart. Reports are stored in folders, which control who has access to them.
Q642. What is a tabular report?
It is the simplest and fastest report format. It displays rows as records and fields listed as columns, just like a spreadsheet. It supports sorting of records but does not support grouping, so it cannot normally be used for dashboard components unless a row limit is set.
Q643. What is a summary report?
A summary report allows the user to group rows of data, summarise the field values, and it also supports sorting and displays subtotals. It is the most commonly used format and can be used in dashboards and charts.
Q644. What is a matrix report?
In a matrix report the records are summarised in a grid format. It allows records to be grouped by both columns and rows, which makes it useful for comparing related totals across two dimensions.
Q645. What is a joined report?
In a joined report, the user can create multiple report blocks that provide different views of the data. The data is organized in the form of blocks, and you can add up to 5 blocks in a single report. Each block is defined by its own report type (a sub-report) and can have its own fields, columns, sorting and filtering.
Q646. What is conditional highlighting in Salesforce reports?
Conditional highlighting is a way to show values in a report within given limits - you specify colours for different ranges of values, so that summary/subtotal values are highlighted according to the breakpoints you define. Up to three colours and two breakpoints can be set, and it requires a summary or matrix report.
Q647. Which field types does a bucket field support?
Bucketing supports the field types Picklist, Number and Text.
Q648. What is a dashboard in Salesforce?
A Salesforce dashboard is the visual representation of snapshots generated from Salesforce report data. Using dashboard components you can convert business requirements into a graphical representation based on reports. Like reports, dashboards are stored in folders, and each component points at a single source report.
A single dashboard can hold up to 20 components, each backed by one source report.
The running user determines which data everyone sees on a standard dashboard; a dynamic dashboard shows data as the logged-in viewer instead.
Q649. What are the different dashboard components?
Scatter Chart, Line Chart, Funnel Chart, Vertical Bar Chart, Donut Chart, Horizontal Bar Chart, Pie Chart, Gauge, Metric, Table and Visualforce Page (plus Lightning components in Lightning Experience).
Q650. What is a workflow, and what are the types of workflow actions?
Workflow rules are automated processes used in business processes to send email alerts, assign a task, update a field, or send an outbound message when rule criteria or evaluation criteria are met.
Types of workflow action:
Task - assign a task to a user.
Email Alert - send an email using a template.
Field Update - update a field on the record or its parent.
Outbound Message - send an outbound SOAP message to an external system.
Actions can be immediate or time-dependent.
Q651. What is an approval process?
An approval process is used to get approvals on records. For example, a user's manager can approve or reject the submitted record. You can define entry criteria, approval steps, approvers, and perform certain actions on initial submission, approval, rejection or recall - such as field updates, email alerts, tasks and outbound messages. Records can also be locked while pending approval.
Q652. What are queues in Salesforce?
A queue lets a single record (such as a Lead or Case) be owned by a group of users rather than an individual, so it can be assigned to multiple users - anyone who is a member of the queue can take ownership and work it. Queues are used with assignment rules and Omni-Channel routing.
Q653. What are auto-response rules?
Auto-response rules automatically send personalised email templates for new cases and new leads coming from your website (Web-to-Case and Web-to-Lead), acknowledging the submission. Only one auto-response rule per object can be active, and the first matching rule entry is used.
Q654. What are escalation rules?
Escalation rules automatically escalate cases to the right people when the cases aren't solved by a certain time. An escalation rule entry defines the criteria and escalation actions (reassign owner, notify users) plus the age-based timing that triggers them.
Q655. What is a time-dependent workflow?
A time-dependent workflow contains time-triggered actions that are scheduled to happen at a later time - for example 7 days after the rule is triggered or 3 days before a close date. Time-dependent actions cannot be used with the evaluation criteria "Evaluate the rule when a record is created, and every time it's edited", and pending actions can be viewed and removed from the Time-Based Workflow queue.
Q656. What are the different types of fields in Salesforce?
Field types define the type of information you expect users to enter into a field. Examples include Text, Text Area, Number, Currency, Percent, Date, Date/Time, Checkbox, Picklist, Multi-select Picklist, Email, Phone, URL, Formula, Roll-up Summary, Lookup, Master-Detail, Geolocation and Auto Number. It is important to match the field type to the data, because the type affects your ability to report on and analyze the data - for example, you could store numbers in text fields, but that would make performing calculations on them needlessly challenging.
Q657. What is a validation rule and where is it configured?
A validation rule verifies that the data a user enters meets the standards you specify before the record is saved. The rule contains a formula that evaluates to true or false: if it evaluates to true, the save is blocked and the error message is displayed. Validation rules are created from Object Manager > Validation Rules, and the limit is 100 active validation rules per object.
Q658. What is Process Builder?
Process Builder is an automated process similar to workflow rules but with extra options - it can create records, update related records, call Apex, send email alerts and custom notifications, post to Chatter, launch a flow and submit records for approval. It supports multiple criteria nodes with different actions per node. (Salesforce has retired Process Builder in favour of Flow.)
Q659. What is a Flow in Salesforce, and what are its types?
A flow is an automation that can accept information from the user and act on data. A screen flow is a set of screens that works quickly - for example quickly creating leads - and is used to accept information from the user, so it suits surveys, feedback and questionnaires. Flows can also run without a UI, triggered by record changes, schedules, platform events or Apex.
The tool used is Flow Builder (previously Visual Workflow / Cloud Flow Designer).
After creating a flow you must also distribute it - for example by placing it on a Lightning home page or record page, a Visualforce tab, a quick action, a button or by calling it from Apex.
Also noted:
Salesforce Flow is a declarative tool for automating business operations. Users do not need to write any code in order to construct and use custom business logic. Flows can create, update or delete records, guide users through screens, call Apex, integrate with external systems and much more. Flows are built in Flow Builder and run either interactively (screen flows) or in the background (auto-launched, record-triggered, schedule-triggered and platform event-triggered flows).
A Flow is a declarative automation tool built in Flow Builder that collects, updates, and creates data and executes logic. Types:
Screen Flow - guides a user through screens; launched from a page, action, utility bar, or community.
Record-Triggered Flow - runs when a record is created, updated, or deleted; can run before save (fast field updates, no extra DML) or after save (related records, actions).
Schedule-Triggered Flow - runs at a set time and frequency for a batch of records.
Platform Event-Triggered Flow - runs when a platform event message is received.
Autolaunched Flow (no trigger) - invoked from Apex, a process, REST API, or another flow; runs in the background with no user interaction.
Q660. What are list views?
List views are the saved queries you present to users to help them review the records that interest them. They are most often found when a user clicks a tab in an app, but they can also be displayed via Lightning components on other Lightning pages. List views can be filtered as needed and display whichever columns are relevant, and users can pin their default list view on each tab. Access is controlled by sharing the list view with everyone, only the creator, or specific groups/roles.
Q661. What is a custom metadata type?
Once primarily a developer tool, custom metadata types have become increasingly useful for admins. Custom metadata is like a custom object, but rather than storing data for your organization, it stores data about your organization. Things like discount rates, blackout dates and sales goals are good use cases. The metadata becomes available in formulas, automation and Apex, and because it is metadata rather than data, records are automatically available in all sandboxes you create or refresh, and deploy with change sets and packages.
Q662. What is Data Loader?
There are many ways to import and export data in bulk from Salesforce - including the Import Wizard, exporting reports, and third-party tools such as dataloader.io - but the Salesforce Data Loader is the original. It is a downloadable client application that is free and provides all of the options you need (insert, update, upsert, delete, hard delete, export and export all), and it can be run from the command line for scheduled jobs.
Also noted:
Salesforce Data Loader is a client tool provided by Salesforce for bulk import and export of data. It is used for inserting, updating, upserting, deleting, hard deleting and exporting records. The primary reason for its use is to efficiently manage large volumes of data within Salesforce, making data migration and regular data maintenance easier and more efficient. It can be run through its UI or from the command line for automation.
Q663. How do you handle data quality in Salesforce Data Loader?
Clean and validate the data before loading. This involves removing duplicates, standardizing data formats, and verifying that the data complies with Salesforce field data types and constraints. Additionally, using the preview and test load options (loading a small sample batch first) helps catch errors before running the full data load. Reviewing the success and error CSV files after each run closes the loop.
Q664. Can Salesforce Data Loader be used for both export and import of data? Describe the process.
Yes, Data Loader can be used for both exporting and importing data.
Exporting: you specify the object, select the fields to export and add criteria (a SOQL WHERE clause), then run Export (or Export All to include Recycle Bin records) and the results are written to a CSV file.
Importing: you prepare a CSV file with the data, choose the operation (insert, update, upsert, delete), map the CSV columns to Salesforce fields, and run the operation; success and error files are produced.
In both cases you can schedule these operations through the command-line interface, or perform them interactively in the UI.
Q665. What are some limitations of using Salesforce Data Loader?
It cannot load more than 5 million records at a time.
Complex relationships between objects need manual intervention - parent records must be loaded first and their Ids or External Ids mapped onto the children.
It depends on and consumes the org's API request limits.
It requires a certain level of technical expertise to operate effectively, plus Java (JRE) installed locally.
It cannot migrate metadata, has no built-in rollback, and its scheduling requires an external scheduler with the CLI.
Q666. Explain the difference between insert and upsert operations in Salesforce Data Loader.
The insert operation adds new records to the database. The upsert operation can both insert new records and update existing ones. Upsert requires a unique identifier - an External Id field or the Salesforce record Id - to determine whether each row should be inserted as a new record or used to update an existing one.
Q667. How do you ensure data security while using Salesforce Data Loader?
Data security is maintained by using secure login credentials (and OAuth rather than username/password plus security token where possible), encrypting data during transfer, and adhering to Salesforce's security standards. It is also important to limit access to the Data Loader and to the data files to authorized personnel only, store the exported CSV files securely, use a dedicated integration user with least-privilege permissions, and regularly audit data access and usage.
Q668. What is the role of the mapping file in Salesforce Data Loader and how is it created?
A mapping file (.sdl) associates the fields in the import file with the fields in Salesforce, ensuring that the data from each column in your import file goes into the correct field. The mapping file can be created manually by specifying the relationships between source and target fields in the mapping dialog and saving it, or generated automatically by Data Loader (Auto-Match Fields to Columns) when the field names in the import file match the Salesforce field names. Saved mapping files can be reused, including from the command line.
Q669. What types of files can be imported using Salesforce Data Loader?
Data Loader supports the import of CSV (comma-separated values) files. This format is widely used because it is compatible with many data exporting tools and can be easily created and edited in spreadsheet programs such as Microsoft Excel or Google Sheets. (It can also read from a database connection when run from the command line.)
Q670. How do you handle errors during data loading in Salesforce Data Loader?
Data Loader logs errors encountered during the data loading process in an error CSV file. To handle these errors you review the error log files generated by the tool, identify the cause of each error - such as data format issues, field mapping errors, missing required fields or validation rule failures - correct the issues in the source file, and then reload only the failed rows.
Q671. Can Salesforce Data Loader update records without an Id?
Yes. Data Loader can update records without Salesforce Ids by using an External Id field. The field must be marked as an External Id in Salesforce and must contain unique record identifiers. The upsert operation is used in this case, relying on the External Id to match and update the correct records (and to insert the row when no match is found).
Q672. Describe the process of scheduling automated data loads using Salesforce Data Loader.
To schedule automated data loads, use the Data Loader command-line interface (CLI). You create the configuration files - process-conf.xml with the process bean parameters, plus the mapping (.sdl) file and an encrypted password key - and then use Windows Task Scheduler (or cron on other operating systems) to run the Data Loader CLI command at the scheduled times.
Q673. What is the significance of the Bulk API in Salesforce Data Loader?
The Bulk API is a Salesforce API designed for processing large sets of data asynchronously in batches. Data Loader can be switched to use the Bulk API for high-volume data operations, enabling faster and more efficient processing of large loads and extractions compared to the traditional SOAP API, and it is required for the hard delete operation. Serial mode can be enabled to avoid record-locking contention.
Q674. How does Salesforce Data Loader support rollback or undo functions?
Data Loader does not have a built-in rollback or undo function. To mitigate this, it is essential to back up the data before performing any major data load operation - typically by exporting the affected records first. In case of error, you can use the backup file to restore the previous state by performing delete or update operations, using the success file's record Ids to target exactly the rows that were changed.
Q675. In what scenarios is it preferable to use Salesforce Data Loader instead of the import wizards provided by Salesforce?
Data Loader is preferred when you need to handle large volumes of data (over 50,000 records), when you need to load into an object not supported by the import wizards, or when you require more complex operations such as upsert, delete, hard delete, export and export all. It is also useful when dealing with relationships between objects, or when automated, recurring data loads are needed via the command-line interface.
Q676. How does Salesforce Data Loader handle character encoding?
Data Loader supports UTF-8 character encoding, which is essential for ensuring that text in languages other than English is imported correctly. When preparing CSV files for import, save them with UTF-8 encoding to avoid problems with special characters or non-Latin scripts. The read/write encoding can also be set in the Data Loader settings.
Q677. Discuss how Salesforce Data Loader can be used for data cleansing.
Data Loader assists in data cleansing by exporting data for analysis and re-importing it after cleansing. You export the data, clean it in an external tool such as Excel - deduplicating, standardizing formats, correcting values - and then use the update or upsert operation to load the cleansed data back into Salesforce, ensuring data accuracy and consistency.
Q678. What are the system requirements to run Salesforce Data Loader?
To run Data Loader you need a system running at least Windows 7 or macOS X, a Java Runtime Environment (JRE 8 or later, or the bundled OpenJDK in newer versions), internet access, and sufficient permissions to install and run the application on the machine. On the Salesforce side, the user needs API Enabled plus the relevant object and field permissions.
Q679. How does Salesforce Data Loader handle relationship fields between records in different objects during import?
Data Loader requires record Ids or External Ids to establish relationships. For direct relationships, the record Id of the parent object must be included in the CSV file for the child. For indirect relationships - where the Salesforce Id is unknown - use an External Id field on the parent and reference it in the child's column header (for example Account:MyExternalId__c) so the records are associated across objects. Load parents before children.
Q680. Explain how you would pass variables between different elements in a Flow.
You pass variables between flow elements using input and output variables and assignments. Output variables from one element - for example the record collection returned by a Get Records element - can be used as input to another element such as a Loop, a Decision or an Update Records element. The Assignment element moves or transforms values between variables, creating a seamless flow of data through the process. Variables marked Available for Input/Output can also pass data in and out of the flow itself and to subflows.
Q681. How do you make a Flow available to users?
Flows can be surfaced in several ways:
Screen Flows - embedded on a Lightning record page, home page or app page, launched from a quick action or custom button, added to an Experience Cloud site, or run from a flow URL.
Auto-launched Flows - triggered by a process or a record update, or called from Apex.
Triggered Flows - invoked by an Apex trigger, a Process Builder, a record change, a schedule or a platform event.
Flow access is also controlled by the "Run Flows" permission or by granting flow access via profiles and permission sets.
Q682. Can you explain how to schedule a Flow to run at a specific time?
Salesforce provides Schedule-Triggered Flows, which run at a specified start date and time with a frequency of once, daily or weekly, optionally against a set of records matching an entry condition. Where a schedule-triggered flow does not fit - for example a per-record delay - you can use a scheduled path in a record-triggered flow, or invoke an auto-launched flow from Apex scheduled with System.schedule. (Historically, before Scheduled Flows existed, this was done with Process Builder or a scheduled Apex class launching the flow.)
Q683. What is the difference between Salesforce Flow and Process Builder, and when would you choose one over the other?
Answer supplied - source left blank.
Process Builder strengths: very simple to build, easy for admins to read for straightforward "when X changes, do Y" rules. Weaknesses: runs only after save, no loops, no screens, no fault handling, poor performance (each process is its own transaction step and it re-queries records), difficult to debug, and it is now retired by Salesforce - no new processes should be built.
Flow strengths: before-save fast field updates (up to 10x faster than Process Builder for same-record updates), loops, collections, subflows, screens for user interaction, fault paths, scheduled paths, platform event and schedule triggers, invocable Apex and HTTP callout actions, and a proper debugger. Weaknesses: more complex to build and to review, easier to hit governor limits if built badly.
When to choose which: for any new automation, choose Flow - Salesforce has ended support for new Process Builder processes and provides a migration tool. Use a before-save record-triggered flow for same-record field updates, an after-save flow for related-record work, a screen flow when the user must supply input, and Apex when the logic is genuinely complex, needs sophisticated error handling, dynamic queries or heavy data volumes. The only reason to touch Process Builder today is maintaining a legacy process until it can be migrated.
Q684. How do you handle record-triggered flows, and what considerations should be taken into account when designing them?
Answer supplied - source left blank.
Key considerations:
Choose the right trigger timing: use a before-save flow for updating fields on the triggering record (no extra DML, much faster); use after-save for creating or updating related records, sending emails, posting to Chatter or calling Apex.
Entry conditions: set precise entry criteria and use "Only when a record is updated to meet the condition requirements" to avoid re-running the flow needlessly and to prevent recursion.
One flow per object per timing where practical, with clear ordering (Trigger Order) so the sequence is predictable and maintainable.
Bulkification: never place Get Records, Create/Update/Delete Records or actions inside a loop; build collections and do the DML once.
Recursion: guard against flows re-triggering each other; use $Record__Prior comparisons and narrow entry conditions.
Governor limits: flows share the transaction limits with triggers and Apex - watch SOQL, DML and CPU time.
Error handling: add fault paths on every element that can fail, and log errors.
Scheduled paths: use them for time-delayed work instead of building loops or polling.
Testing and deployment: debug with real record data, and test bulk scenarios with 200-record data loads.
Q685. Explain flow bulkification: why is it important, and how do you ensure your Flow is bulk-safe?
Answer supplied - source left blank.
Bulkification means the flow processes many records in a single transaction using the same number of queries and DML statements as it would for one record. When 200 records are loaded at once, a record-triggered flow runs as a single bulk interview batch; the platform automatically groups the interviews, but only elements outside loops are batched together.
Why it matters: without it you hit the transaction governor limits - 100 SOQL queries, 150 DML statements, 10,000 ms CPU - and the whole data load fails with an "Apex CPU time limit exceeded" or "Too many SOQL queries" error.
How to make a flow bulk-safe:
Never put a Get Records, Create Records, Update Records, Delete Records or Apex/email action inside a Loop element.
Inside the loop, only use Assignment elements to add records to a collection variable; perform a single DML on the collection after the loop.
Query once before the loop and use a collection or a Loop + Decision to match records, rather than querying per iteration.
Keep formulas and complex logic simple to limit CPU consumption.
Test by loading 200 records with Data Loader and by running the flow's debug with bulk data.
Q686. Can you provide an example of using dynamic record choice elements in a screen flow?
Answer supplied - source left blank.
A Record Choice Set dynamically populates a screen picklist or radio group with records queried at run time, instead of hardcoded choices.
Example - let a user pick one of the open Cases on the current Account:
1. Create a Record Choice Set resource named openCaseChoices.
2. Object: Case. Filter conditions: AccountId Equals {!recordId} and Status Not Equal To Closed.
3. Choice Label: CaseNumber (or a formula combining CaseNumber and Subject). Choice Value: Id (data type Text).
4. Optionally sort by CreatedDate descending and set a limit.
5. Store additional field values: assign Subject to a variable varSelectedSubject so the flow can use the chosen record's other fields.
6. On the screen, add a Picklist/Radio Buttons component and set its Choice to openCaseChoices.
7. The selected value (the Case Id) is available downstream in {!Case_Picklist} and can feed a Get Records or Update Records element.
A Collection Choice Set is the modern alternative: query the records once with Get Records, then build choices from the resulting collection, which is more efficient when you already have the data.
Q687. How do you handle dependent picklists or dynamic choices in Salesforce Flow screens?
Answer supplied - source left blank.
Options, from simplest to most flexible:
Standard dependent picklists: if the fields are configured as controlling/dependent picklists on the object, use the Record-based screen components (Picklist fields via a Record field on the screen, or lightning-record-edit-form in a custom LWC) - the dependency is honoured automatically.
Reactive screens (Screen Flow reactivity): in recent releases, a second picklist's Record Choice Set filter can reference the value chosen in the first component on the same screen, so the choices update reactively without splitting the screens.
Two screens: capture the controlling value on screen 1, then use a Record Choice Set or Collection Choice Set on screen 2 whose filter references the value selected on screen 1.
Get Records + Collection Choice Set: query the child records filtered by the controlling selection, then build the choices from that collection.
Apex-backed: an @InvocableMethod returning the dependent values, or a custom LWC screen component that queries the dependent picklist entries and handles the cascade entirely on the client.
Always handle the "no matching values" case with a Decision so the screen does not present an empty picklist.
Q688. How do you handle errors and exceptions in Salesforce Flow?
Answer supplied - source left blank.
A robust approach:
Add fault connectors to every element that can fail: Get Records, Create/Update/Delete Records, Apex actions, HTTP callout actions, submit-for-approval and email actions.
Screen flows: route the fault path to an error screen that shows a friendly message plus {!$Flow.FaultMessage} so the user knows what happened and what to do next.
Auto-launched and record-triggered flows: route the fault path to a Create Records element that writes the fault message, the record Id and the flow name to a custom logging object, and optionally send an email alert or a custom notification to the support team.
Validate before acting: use Decision elements to check for nulls, empty collections and required values before DML, so predictable problems never become faults.
Design for partial failure: process collections and decide whether one bad record should stop everything; log and continue where appropriate.
Monitor: check Setup > Paused and Failed Flow Interviews, and keep the "Send an email to the admin" fault email setting configured for a real distribution list.
Test the fault path explicitly in debug by forcing an error (for example a validation rule violation).
Also noted:
Exception handling in Salesforce Flow is managed using Fault Paths. When an error occurs in a Flow element, execution is directed to a Fault Path where specific actions can be defined, such as sending error notifications or logging the error details. This ensures that exceptions are caught and handled gracefully, maintaining the integrity of the Flow's operation.
Q689. How can you optimize the performance of a Flow?
Answer supplied - source left blank.
Best practices:
Use before-save record-triggered flows for same-record field updates - they avoid an extra DML and are dramatically faster than after-save automation.
Keep queries and DML outside loops; build collections and do a single Create/Update at the end.
Query only what you need: set the Get Records element to return only the fields you use, filter tightly, and choose "Only the first record" when one record is enough.
Set precise entry conditions so the flow does not run on irrelevant records, and use "only when the record is updated to meet the conditions" to avoid repeated firing.
Avoid deep nesting and unnecessary loops; use collection filters and Decision elements instead of scanning collections.
Consolidate automation per object rather than having many flows all firing on the same event, and control flow trigger order.
Move genuinely heavy processing to Apex (batch/queueable) or to the asynchronous path of a record-triggered flow.
Debug with realistic volumes and review the flow's CPU consumption in debug logs.
Also noted:
Minimizing the number of elements and unnecessary logic.
Using loops efficiently and avoiding nested loops.
Leveraging Fast Lookup and Fast Create for bulk operations.
Avoiding hard-coded IDs or values and using variables and formulas instead.
Testing the Flow thoroughly in bulk scenarios to ensure it does not hit governor limits.
Q690. What are the main components of a Flow?
The main components of a flow include:
Elements - the building blocks of the flow, such as creating records, updating records, making decisions, loops, assignments and displaying screens.
Resources - variables, constants, formulas, choices, text templates and sObject variables that store and manipulate data within the flow.
Connectors - define the path of execution between elements, including fault connectors for error paths.
Q691. How are screen flows different from auto-launched flows?
Screen flows are designed to interact with users - they can display information, collect user data through screens, and guide users through steps. Auto-launched flows, on the other hand, are designed to run in the background without any user interaction, typically triggered by an event such as a record creation or update, a schedule, a platform event or an Apex call. Auto-launched flows cannot contain screen elements.
Q692. How can you trigger a Flow to run automatically?
You can trigger a flow automatically using several methods:
Record-triggered flows (create, update, delete)
Schedule-triggered flows (to run at specific intervals)
Platform event-triggered flows
Process Builder
Workflow rules (less common, since Process Builder and Flow provide more functionality)
Apex code (Flow.Interview / start())
Invocable actions from other flows (subflows) and from the API
Q693. Can you call an Apex class from a Flow?
Yes. You can call an Apex class from a flow using the Apex Action element, which invokes a method annotated with @InvocableMethod. This enables you to extend the usefulness of flows with custom Apex logic - complex calculations, callouts, or work that is impractical declaratively. Apex-defined data types can also be passed in and out.
Q694. What are the limitations of Salesforce Flow?
Some limitations of Salesforce Flow include:
A limited loop iteration count (for example around 2,000 iterations per interview).
A limited number of SOQL queries and DML statements per flow execution, since flows share the transaction governor limits.
Some complex operations still require Apex code.
Flows cannot be used in certain scenarios where triggers are required, and have limited control over execution order relative to other automation.
Limited unit-testing capability compared with Apex, and merge/version-control friction on the XML.
Also noted:
Limited support for certain objects and features compared with Apex.
Complexity in handling large data volumes - flows are subject to the same governor limits as Apex, and loops with DML or queries inside can quickly hit them.
Limited integration capabilities compared with Apex - external callouts from flows are constrained (HTTP callout actions or invocable Apex are needed).
A cap on loop iterations, limited debugging compared with Apex, and no true unit-test framework.
Q695. What is a subflow?
A subflow is another flow invoked from within a main flow. It allows a modular design, where you create reusable components and logic by encapsulating them into separate flows and invoking them as subflows, passing values in and out through input and output variables. Only auto-launched flows and screen flows can be used as subflows, and the subflow must match the parent's type (a screen flow can call a screen flow or an auto-launched flow).
Q696. How can you debug a Flow?
Salesforce provides a debug tool within Flow Builder. You can run the flow in debug mode, set input variable values (including choosing a real record for a record-triggered flow), and step through the flow's execution while seeing the value of every resource at each step. There is also a "Debug in rollback mode" option so changes are not committed. In addition, debug logs and the flow's interview logs (Setup > Paused and Failed Flow Interviews) provide insight into any issues, and the flow error email gives the failing element and fault message.
Q697. What is the difference between a Record-Triggered Flow and a Scheduled Flow?
A Record-Triggered Flow is initiated when a specific event related to a record occurs, such as when a record is created, updated, or deleted. A Scheduled Flow runs at specified intervals (for example, daily or weekly) and operates on the records that meet the defined criteria.
Q698. Can Flows replace Apex Triggers?
Flows can handle many automation scenarios traditionally managed by Apex Triggers, but they can only partially replace them. Apex Triggers are more flexible and can handle more complex scenarios, especially those involving deep integrations, complex calculations, or operations outside the Salesforce platform. However, using Flows for declarative automation can reduce code and improve maintainability.
Q699. What are Fast Lookup and Fast Create in Flows?
Fast Lookup and Fast Create are elements designed for bulk processing in Flows.
Fast Lookup: retrieves numerous records at once and stores them in an sObject collection variable.
Fast Create: allows you to create multiple records at once using an sObject collection variable.
Q700. How do Before-Save Record-Triggered Flows differ from After-Save Record-Triggered Flows?
Before-Save Record-Triggered Flows are initiated before a record is saved to the database. This means they can modify the record without needing an additional DML operation, which makes them more efficient. After-Save Record-Triggered Flows run after the record is saved and are suitable for actions that should happen post-save, such as sending notifications or creating related records.
Q701. What are Local Actions in Flows?
Local Actions in Flows allow users to execute Lightning Component Actions within a Flow. This can be used to extend the capabilities of Flows with custom Lightning Components or to invoke standard Lightning actions.
Q702. Can Flows be used in Communities?
Yes. Flows can be embedded in Lightning Communities using the Flow component. This allows community users to interact directly with Salesforce data and processes from the community interface.
Q703. What is the role of the "Assignment" element in Flows?
The "Assignment" element assigns values to variables or sObject fields within the Flow. It can be used for calculations, data transformations, or setting values before creating or updating records.
Q704. How do you ensure data integrity when using Salesforce Flow?
To maintain data integrity in Salesforce Flow it is crucial to implement robust validation within the Flow. This includes:
Checking for null values.
Ensuring data formats are correct.
Using Decision elements to validate data before performing operations such as record updates or creations.
Incorporating error handling mechanisms (Fault Paths).
Testing the Flow extensively across various scenarios.
Q705. What is the significance of versioning in Salesforce Flow?
Versioning in Salesforce Flow allows for the creation of multiple versions of the same Flow. This is crucial for updating or modifying Flows without disrupting the existing business process. Each time a Flow is edited, a new version is created, enabling administrators to revert to previous versions if needed. Versioning also aids in tracking changes over time and understanding the evolution of the Flow's logic.
Q706. How does Salesforce Flow support mobile responsiveness?
Salesforce Flow supports mobile responsiveness by allowing the creation of Flows that adapt to different screen sizes and devices. When designing a Flow, especially with screen elements, designers can use the Lightning Design System to ensure that the Flow's user interface is responsive and provides an optimal experience on both desktop and mobile devices.
Q707. What role does a Loop play in Salesforce Flow, and how do you use it effectively?
In Salesforce Flow, a Loop is used to iterate over a collection of records or values. It is effective for processing multiple records in batches, such as updating a list of contacts or aggregating data. To use it effectively, ensure the loop does not exceed governor limits by processing records in manageable batches and optimizing the logic inside the loop to avoid unnecessary processing.
Q708. Can you explain how Scheduled-Triggered Flows work in Salesforce?
Scheduled-Triggered Flows are designed to execute at specified times, such as daily or weekly, without manual intervention. They are useful for routine tasks like monthly data cleanups or regular data analysis. These Flows are set up by defining the frequency, start date, and the conditions under which the Flow should run, making them a powerful tool for automating time-based processes.
Q709. What is the purpose of Record-Triggered Flows with Before Save updates?
Record-Triggered Flows with Before Save updates allow you to make changes to a record before it is saved to the database. This is particularly efficient for field updates because it does not require additional DML operations, reducing processing time and resource consumption. It is ideal for scenarios where quick field modifications are needed based on certain record conditions.
Q710. In what scenarios would you use a Subflow in Salesforce Flow?
A Subflow is used to modularize and reuse logic. It is ideal in scenarios where the same set of actions or logic is required in multiple Flows. By encapsulating this logic in a Subflow, you can maintain it in one place and call it from various parent Flows, enhancing maintainability and reducing redundancy.
Q711. Explain the Decision element in Salesforce Flow.
Decision elements allow for branching logic based on specified criteria. They enhance process automation by enabling the Flow to take different paths or actions depending on data conditions or user inputs. This is akin to if-else statements in programming and is crucial for creating dynamic, condition-based automated processes in Salesforce.
Also noted:
The Decision element branches the flow's logic based on criteria. It evaluates one or more outcomes, each with its own conditions, and directs the flow's execution path down the first outcome whose conditions are met - falling through to the default outcome if none match. It is similar to if-else logic in programming.
Q712. How do you bulk delete or clean records in Salesforce?
Answer supplied - source was incomplete.
Options for bulk deleting and cleaning records:
Mass Delete Records (Setup > Data > Mass Delete Records) for standard objects, up to 250 records at a time.
Data Loader with the delete or hard delete operation - hard delete bypasses the Recycle Bin (requires Bulk API enabled).
Bulk API delete / hardDelete jobs for very large volumes.
Batch Apex using Database.Batchable with a QueryLocator, deleting in scopes of 200, which can process up to 50 million records.
Empty the Recycle Bin afterwards to reclaim storage (DELETE in Data Loader hard delete or Setup > Empty Recycle Bin).
For data cleansing, use duplicate rules/matching rules or a third-party duplicate-checker AppExchange package before deletion.
Q713. Scenario: how do you send a notification to the seniors (managers) on an Opportunity?
Asked at: GenPact
Using a workflow rule with an email alert action we can send the notification to the owner's manager or to a defined set of recipients.
The same is now done with Record-Triggered Flow + Send Email / Send Custom Notification, since workflow rules are being retired.
The recipient can be set to Owner's Manager, a role, a public group, or an email field on the record.
Q714. How do you use record types to create picklists?
Asked at: GenPact
Record types are configured from the admin setup (Object Manager > Record Types). A record type is tied to a picklist value set and a page layout, so different profiles can see different picklist values and layouts for the same object.
Create the record type, choose which picklist values are available for it, then assign the record type to profiles and set the default per profile.
Q715. What is a dynamic approval process?
Asked at: Accenture
Answer supplied - source left blank.
A dynamic approval process is an approval process whose approver is worked out at run time from the record's own data instead of being hard-coded in the step.
On the approval step choose Related User or Let the submitter choose the approver, or point the step at a hierarchy/lookup field on the record (a User lookup such as Regional Manager).
The usual pattern is a custom User lookup field on the object populated by a workflow field update, Process Builder or Flow just before submission, and the approval step set to Automatically assign to approver(s) > Related User > that field.
This lets one approval process route to different approvers based on amount, region, product, and so on, rather than building a separate process per case.
Also noted:
There is no feature literally called a "Dynamic Approval Process". What is meant is an approval process where the approver is determined dynamically at runtime based on conditions - for example, by using a hierarchy field or a custom user lookup field on the record as "Related User", or by setting the approver via entry criteria and step criteria in the approval process.
Q716. What is the assignment process in Salesforce?
Assignment rules - Case Assignment Rules automatically assign cases to agents or queues, and Lead Assignment Rules automatically assign leads to users or queues based on defined criteria.
Q717. Will one workflow rule affect another workflow rule?
Asked at: Accenture
Answer supplied - source left blank.
Yes, it can.
All workflow rules whose criteria are met fire in the same transaction, and their order is not guaranteed.
If a workflow field update changes a field, it can cause re-evaluation: when Re-evaluate Workflow Rules After Field Change is ticked on the field update, all workflow rules on the object are evaluated again, which can fire a second rule (and can even loop - Salesforce stops after a limited number of re-evaluations).
A field update also re-fires before and after triggers, so a workflow can indirectly cause trigger and validation-rule logic to run again.
Because of this, workflow field updates on the same field from two rules can overwrite each other.
Q718. How can you convert a lead?
Asked at: Accenture
Answer supplied - source left blank.
A qualified Lead is converted into an Account, a Contact and (optionally) an Opportunity.
UI: open the Lead and click Convert; choose an existing or new Account/Contact, decide whether to create an Opportunity, set the converted status and record owner.
Apex: use Database.LeadConvert:
Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(leadId);
lc.setConvertedStatus('Closed - Converted');
lc.setDoNotCreateOpportunity(false);
Database.LeadConvertResult lcr = Database.convertLead(lc);
Custom lead fields must be mapped (Setup > Lead > Fields > Map Lead Fields) to carry data across; unmapped data is lost.
After conversion the Lead becomes read-only (IsConverted = true).
Q719. In which scenario do we prefer to use Custom Settings?
Asked at: Cloud 360
Custom Settings are used for data that is looked up frequently and needs to be cached in the application cache rather than queried - and they can vary per profile or per user.
Hierarchy custom settings: environment-specific values, feature switches, and per-profile/per-user overrides (for example credentials, endpoints, batch sizes).
List custom settings: small reference data such as country codes or discount rates.
They can be read without a SOQL query (MySetting__c.getInstance()), so they do not count against SOQL limits.
Q720. In which scenario do we prefer to use Custom Metadata Types?
Asked at: Cloud 360
When we need to store static data about the organisation - metadata, not data: discount rates, blackout dates, sales targets, integration endpoints, validation thresholds.
Because it is metadata it is deployable through change sets/packages and is automatically present in every sandbox that is created or refreshed.
It is available in formulas, validation rules, flows and Apex, and Apex reads are not counted against SOQL limits.
Records are read-only in Apex at runtime (they are edited in Setup or deployed), which is the main difference from Custom Settings.
Also noted:
When you have to store static configuration data (metadata about data) that should be deployable between orgs as metadata - for example mapping tables, business rules, and settings that are packaged and migrated along with the code.
Q721. What is the difference between Workflow, Process Builder, and Flow?
Answer supplied - source left blank.
Workflow Rule: the oldest tool. Fires on create/edit, supports only four actions - field update, email alert, task creation, and outbound message. It can update the same record or the parent in a master-detail relationship only. No branching logic, no record deletion, no ordering.
Process Builder: supports multiple criteria nodes evaluated in order, can update any related record, create records, submit for approval, post to Chatter, launch a Flow, and call Apex via @InvocableMethod. It cannot delete records and has no user interface.
Flow: the most powerful and the strategic tool. Supports screens for user interaction, loops, decisions, assignments, get/create/update/delete records, subflows, fault paths, before-save fast field updates (which are far more performant than Workflow/Process Builder), scheduled and platform-event-triggered execution, and calling Apex.
Salesforce has retired Workflow Rules and Process Builder in favour of Flow, so all new automation should be built in Flow.
Q722. What are the types of workflow actions and how do you set them up?
Answer supplied - source left blank.
A workflow rule has an evaluation criterion (created; created and every time it is edited; created, and any time it is edited to subsequently meet criteria), a rule criterion (filter or formula), and workflow actions.
The four workflow actions are:
Field Update - updates a field on the same record or on the parent of a master-detail relationship; can optionally re-evaluate workflow rules.
Email Alert - sends an email using an email template to specified recipients.
Task - creates a task assigned to a user, role, or record owner.
Outbound Message - sends a SOAP message with selected field values to an external endpoint.
Actions can be immediate or time-dependent (queued in the time-based workflow queue relative to a date field). Setup path: Setup > Process Automation > Workflow Rules > New Rule > select object > set evaluation and rule criteria > add immediate or time-dependent actions > Activate.
Q723. What can cause data loss in Salesforce?
Causes of data loss:
Accidental deletion
Data import/export issues
Integration errors
Apex code and triggers
System upgrades and changes
Governor limits
Changing a field's data type (for example converting to a type that truncates values)
Best practices to prevent data loss: regular backups, version control and testing, and governor limit awareness.
Q724. Can we create a dependent picklist in a Flow?
Yes, we can. Screen Flows support dependent picklists on record fields, and dependent choices can also be built using picklist choice sets.
Q725. What is a time trigger?
A setting that defines when time-dependent workflow actions should fire.
Q726. Can a user insert their own custom logo while creating their own custom applications?
Yes. The user can upload their custom logo in Documents and then choose that logo for the organization/application.
Q727. List the things that can be customized on page layouts.
We can customize different things on a page layout, such as:
Fields
Buttons
Custom links
Related lists
We can also create sections.
Q728. List examples of custom field types.
Text, Picklist, Picklist (Multi-Select), Date, Email, Date/Time, Currency, Checkbox, Number, Percent, Phone, URL, Text Area, Geolocation, Lookup Relationship, Master-Detail Relationship, and so on.
Q729. In how many ways can we make a field required?
While creating the field
Validation rules
Page layout level
Q730. What is field dependency?
Field dependency means that, according to the field selection on one field, the picklist values on another field are filtered.
Q731. Can a checkbox act as a controlling field?
Yes, it is possible. A controlling field should be either a checkbox or a picklist.
Q732. What are record types?
Record types restrict the picklist values and assign different page layouts for different record types.
Q733. What are the different types of reports available in Salesforce?
There are 4 types of reports in Salesforce:
Tabular Reports
Summary Reports
Matrix Reports
Joined Reports
Q734. What are assignment rules in Salesforce?
Asked at: Accenture
Answer supplied - source left blank.
Assignment rules automatically assign Leads and Cases to a user or a queue as they are created or updated.
Each object can have many rules but only one active rule at a time; a rule contains ordered rule entries, and the first entry whose criteria match wins.
Lead assignment rules run on lead create/edit (and on web-to-lead and imports) when Assign using active assignment rule is checked; case assignment rules run for Web-to-Case, Email-to-Case and manual creation with the checkbox ticked.
Each entry can also send an email notification using a template.
From Apex you must set the rule explicitly with Database.DMLOptions.assignmentRuleHeader.
Q735. What do you do if you need roll-up summaries on a lookup relationship?
Sometimes you would like to aggregate child data on a parent record but cannot use master-detail because the security implications do not suit the use case. In those situations you can:
Write Apex code (a trigger on the child that recalculates the parent field), or
Use Flow Builder to replicate the roll-up summary functionality, or
Install an AppExchange app to make the configuration easy - for example Rollup Helper or Declarative Lookup Rollup Summary (DLRS). Install it in a sandbox first.
Q736. For which workflow evaluation criteria can a time-dependent workflow action not be created?
A time-dependent workflow action cannot be created when the rule evaluation criteria is set to "created, and every time it's edited".
Q737. What happens upon lead conversion?
When a lead is converted, a Contact, an Account and (optionally) an Opportunity are created.
Q738. What are dynamic dashboards?
Dynamic dashboards are dashboards that run in the context of the logged-in user, so each viewer sees the data they have access to, rather than the data of a fixed running user.
Q739. Can dynamic dashboards be scheduled?
No, dynamic dashboards cannot be scheduled for refresh.
(Note: Salesforce later added the ability to schedule dynamic dashboard refreshes in Lightning Experience for supported editions, so check the current release for your org.)
Q740. How many active assignment rules can you have on Lead or Case?
You can have only one active assignment rule at a time per object.
Q741. How can you monitor the pending actions of a time-based workflow?
Navigate to Setup -> Administration Setup -> Monitoring -> Time-Based Workflow.
Q742. How can you compare the value of a picklist field in a validation rule?
Use the ISPICKVAL function.
ISPICKVAL(picklist_field, text_to_compare)
Q743. How can you skip the record type selection page (and use the default record type) while creating a new record of a particular object?
Tick the checkbox against the object under: Setup -> My Personal Information -> Record Type Selection -> check against the required object.
Q744. What data types can the standard Record Name field have?
The Record Name field can be one of two data types: Auto Number or Text.
Q745. What are the different types of email templates that can be created in Salesforce?
Text
HTML (using a letterhead)
Custom (without a letterhead)
Visualforce
Q746. How can you display different picklist values for the same picklist field on different page layouts?
This is done using record types, since each record type can have its own set of available picklist values, and each record type is associated with a page layout.
Q747. What data types can be returned by a formula field?
Checkbox
Currency
Date
Date/Time
Number
Percent
Text
Q748. What are custom labels in Salesforce?
Custom labels are custom text values that can be accessed from Apex code and Visualforce pages. They can be translated into any language Salesforce supports, which makes them useful for multilingual applications.
Q749. What is the character limit of a custom label?
A custom label can be only 1,000 characters long, no more than that.
Q750. Can you edit a formula field value on a record?
No, formula fields are read-only and cannot be edited; their value is calculated at runtime.
Q751. Can you edit a roll-up summary field value on a record?
No, roll-up summary fields are read-only and cannot be edited.
Q752. How can you display an image as a field on the detail page of a record?
Use a formula field with the IMAGE() function, passing the URL of an image stored in Documents (or a static resource) to the function.
Q753. On which objects can you create queues?
Queues can be created on standard objects such as Lead and Case, and on all custom objects.
(Note: Salesforce also supports queues on some additional standard objects, including Order, Service Contract and Knowledge Article Version.)
Q754. What is a mini page layout?
A mini page layout defines the fields and related lists to be displayed in the hover detail and in the console tab. When you hover the mouse over a recently viewed record, the fields configured in the mini page layout are displayed (related lists are not shown in hover detail). The console tab's fields and the related lists on the right-hand side are also controlled by the mini page layout.
Q755. What is the use of the console view / console tab?
The console gives list views and related list records for multiple objects on a single screen, without any customisation (no Visualforce page or controller required).
Q756. What is the difference between a List type custom setting and a Hierarchy type custom setting?
List type stores static data that can be used in Apex code as it is - for example country codes or currencies.
Hierarchy type stores data that may vary depending on the user, the profile or the org-wide default, and resolves the value using that hierarchy.
Q757. Where can custom setting data be accessed?
Custom setting data can be accessed in formula fields, validation rules, workflow rules, Apex and the API.
Q758. How many custom fields can be created on an object?
The initial limit is 500 custom fields, and if needed this can be extended to 800 by raising a case with Salesforce.
Q759. In analytic snapshots, can the target object have a trigger?
If the target object has a trigger on it, the analytic snapshot will fail.
Q760. What are the different custom tabs that can be created in Salesforce?
Three types of tabs can be created:
Custom object tab
Visualforce tab
Web tab
Q761. Can you have assignment rules on custom objects?
No, custom objects do not support assignment rules; assignment rules are available only for Leads and Cases.
Q762. Can an analytic snapshot continue working properly if the running user is deactivated?
No, the snapshot will fail if the running user is inactive.
Q763. Can you import User data through the Import Wizard?
No, this cannot be done. The Import Wizard does not support the User object.
Q764. Can you import custom object data through the Import Wizard?
Yes, custom object data can be imported using the Import Wizard.
Q765. What is a workflow rule and what are its evaluation criteria?
A workflow rule is an automated process built from two parts:
Criteria - the condition that must be met.
Action - immediate actions or time-dependent actions (field update, email alert, task, outbound message).
Evaluation criteria
Created - the rule is evaluated only when a record is created.
Created, and every time it's edited - evaluated on creation and on every update (non-meeting to meeting and meeting to meeting). Time-dependent actions cannot be added with this option.
Created, and any time it's edited to subsequently meet criteria - evaluated on creation and on updates only when the record moves from not meeting the criteria to meeting them.
Other points:
Workflow works on DML - only insert and update.
Governor limit: 500 rules per object, of which 50 can be active at a time.
A workflow field update works on a master-detail relationship (cross-object) but not through a lookup.
Q766. How would you send an email automatically when a form is filled in and a certain condition is met?
Combine three pieces of declarative configuration:
Workflow rule (or Process Builder) on the object, with the evaluation criteria and the rule criteria that describe the condition.
Email template - Setup > Quick Find > Classic Email Templates > New Template - which defines the content of the mail.
Email alert - which selects the template and the recipients, and is then added as the immediate (or time-dependent) action of the workflow rule.
When the record is saved and the criteria are met, the workflow rule fires the email alert and the templated email is sent.
Q767. What are the different report formats in Salesforce?
Tabular - records are simply listed in rows and columns. You cannot create groupings, and it cannot be used on a dashboard unless a row limit is set. The "Show me" and date filters are mandatory by default.
Summary - records are grouped by rows. Grouping rows is mandatory to add a chart. Charts can be added and the report can be shown on a dashboard.
Matrix - records are grouped both row-wise and column-wise. Charts can be added and the report can be shown on a dashboard.
Joined - lets you compare different blocks of data coming from different report types in one report; you select "Joined report" from the report format drop-down.
A report type is the template that gives the structure to a report; report types can be standard or custom. Reports feed charts, which feed dashboards, and reports can be subscribed to / scheduled by email (Edit > Subscription).
Q768. Can a Salesforce report be exported to PDF?
A report itself can only be exported in Excel (.xls) or CSV (.csv) format - there is no "Export to PDF" option on the report.
To get a PDF you either use the browser's Print / Printable View option and print to PDF, or place the report on a dashboard and use the "Save as PDF" option of the dashboard.
Q769. How do you find and restore a deleted custom object?
Deleted custom objects are not removed immediately - they are kept for 15 days and can be restored during that window.
In Salesforce Classic go to Setup > Object Manager (Setup > Create > Objects in older releases); at the bottom of the object list there is a Deleted Objects section listing the objects that have been deleted.
Click Undelete next to the object to restore it together with its data, or Erase to remove it permanently.
Deleted records behave the same way: they stay in the Recycle Bin for 15 days before being purged.
Q770. What is the difference between Custom Settings and Custom Metadata Types?
Custom Settings
Used to create and manage custom data at the organization, profile and user levels (hierarchy custom settings) or as a keyed list (list custom settings).
The data is stored in the application cache, so it can be accessed efficiently without the cost of repeated queries - accessing it does not count against SOQL governor limits (up to about 2 MB of cached data).
Can be used by formula fields, validation rules, Visualforce, Apex, flows and the Web Services API - a common use is a switch to deactivate a trigger in production.
No page layouts, no lookups, no long text area fields, no validation rules, no triggers or workflow on them.
Only the definition is deployable - the records are data and cannot be deployed.
Custom Metadata Types
Treated like an object; you create custom fields on it and create records ("Manage records").
Supports validation rules, page layouts, lookups (metadata relationships) and long text area fields.
Records are metadata, so they are deployable through change sets and packages - which makes them the right place for configuration such as endpoints, mappings and dependent picklist values that must move between orgs.
Queried with SOQL, but those queries do not count against SOQL governor limits.
Setup > Custom Metadata Types > New (label and name are required and must be unique).
Q771. How do hierarchy custom settings behave, and what is the difference between getValues(), getInstance() and getOrgDefaults()?
A hierarchy custom setting can hold values at three levels: User, Profile and Organization. Under the hood these are three different rows, distinguished by the SetupOwnerId column.
Take a setting Car__c with fields Make__c and Model__c, and these Ids:
org id: 00Dxxxxxxxxxxxx
profile id: 00exxxxxxxxxxxx
user id: 005xxxxxxxxxxxx
The table might look like this:
SetupOwnerId Make__c Model__c
<null> Ford
00exxxxxxxxxxxx Taurus
005xxxxxxxxxxxx Toyota
getValues() always returns the individual row, exactly as stored:
getValues('00Dxxxxxxxxxxxx') ==> make=Ford, model=null, setupownerid=null
getValues('00exxxxxxxxxxxx') ==> make=null, model=Taurus, setupownerid=00exxxxxxxxxxxx
getValues('005xxxxxxxxxxxx') ==> make=Toyota, model=null, setupownerid=005xxxxxxxxxxxx
getInstance() and getOrgDefaults() roll the rows up through the hierarchy:
getInstance('00Dxxxxxxxxxxxx') / getOrgDefaults() ==> make=Ford, model=null, setupownerid=null
getInstance('00exxxxxxxxxxxx') ==> make=Ford, model=Taurus, setupownerid=00exxxxxxxxxxxx
getInstance('005xxxxxxxxxxxx') / getInstance() ==> make=Toyota, model=Taurus, setupownerid=005xxxxxxxxxxxx
getInstance/getOrgDefaults always return a row whose SetupOwnerId is the Id passed in (null for getOrgDefaults, the running user's Id for the no-argument getInstance), even if no such row exists in the database. What you get back is therefore a derivative of what is stored, potentially merged from several rows.
Rule of thumb: use getValues() when you are writing custom settings, and getInstance() when you are reading them.
Q772. In the App Launcher, how do you show or hide the items shown under All Items for a specific profile?
Control it through the Profile. The App Launcher only shows the apps and tabs that the running user's profile can see, so:
Set the tab visibility (Default On / Default Off / Tab Hidden) for each object on the profile.
Assign or remove the connected apps and Lightning apps from the profile's assigned apps.
Anything the profile cannot access does not appear in the App Launcher's All Items list.
Testing, Deployment & DevOps
63 questions
Q773. How do you test future methods?
To test future methods, enclose your test code between the startTest and stopTest test methods. The system collects all asynchronous calls made after startTest. When stopTest is executed, all these collected asynchronous processes are then run synchronously. You can then assert that the asynchronous call operated properly.
Q774. How do you test batch Apex?
Code is run between Test.startTest() and Test.stopTest(). Any asynchronous code included within Test.startTest and Test.stopTest is executed synchronously after Test.stopTest.
Q775. How many records can we insert while testing batch Apex?
We have to make sure that the number of records inserted is less than or equal to the batch size of 200, because test methods can execute only one batch. We must also ensure that the Iterable returned by the start method matches the batch size.
Q776. Can you customize Apex and Visualforce directly in a production org?
Apex cannot be customized in a production org. It must be changed in a sandbox or developer org and deployed to production, meeting the required test coverage. Visualforce, on the other hand, may be customized directly in production (although this is not best practice).
Q777. What is a sandbox org in Salesforce, and what are the different types?
Sandboxes are copies of the production organisation. It is possible to make multiple copies of the same environment that serve various purposes - development, testing and training - without any need to compromise the data in the production org. As sandboxes are isolated from production, operations performed in a sandbox have no impact on the production org.
There are four types of Salesforce sandbox:
Developer Sandbox
Developer Pro Sandbox
Partial Data Sandbox
Full Sandbox
Also noted:
A sandbox is a copy of your production org, used for development, testing and training without affecting production data and applications. (Depending on the sandbox type, it may be a copy of metadata only or of metadata plus some or all data.)
Q778. Is it possible to edit an Apex class or trigger in the production environment?
No. We cannot directly edit an Apex class or trigger in the production environment. It can be done only in a Developer Edition org, a sandbox org or a testing org, and then deployed to production with at least 75% code coverage.
Q779. What is the Developer Console?
The Developer Console is an integrated development tool with a collection of tools that can be used to create, debug and test applications in your Salesforce org - a source-code editor, a Query Editor for SOQL/SOSL, the Log Inspector for debug logs, the Test runner and code coverage, anonymous Apex execution, checkpoints and the View State inspector.
Q780. What are packages, what are the types of packages, and what are managed packages?
A package is a bundle or collection of components or related applications that can be distributed as a unit.
There are two classic types of package:
Managed - used to sell and distribute applications to customers. Developers can sell user-based licences and applications through the AppExchange. Managed packages are fully upgradable, their code is hidden from the subscriber, and certain destructive changes (such as removing objects or fields) are restricted to keep upgrades seamless.
Unmanaged - the components are delivered once and then behave as if they had been created in the subscriber org; they are editable and are not upgradable.
(Modern development also uses unlocked packages and second-generation managed packages built with the Salesforce CLI.)
Q781. What are the development tools for Apex?
The development tools for Apex are the Force.com Developer Tools, the Force.com IDE (Eclipse) and the Code Editor (Developer Console). Today the standard tooling is Visual Studio Code with the Salesforce Extension Pack and the Salesforce CLI (sfdx).
Q782. What is the use of a debug log?
A debug log is used to catch and diagnose exceptions and to see what happened during a transaction - it records database operations, system processes, callouts, validation rules, workflow, and errors, together with System.debug() output. Logs are set up per user with trace flags and debug levels at Setup > Debug Logs, and are viewed in the Developer Console's Log Inspector.
Q783. What is Apex Hammer?
Before each major service upgrade, Salesforce runs all Apex tests on customers' behalf through a process called Apex Hammer. The tests are executed in both the current and the next release across all orgs, and the results are compared, so that any regression introduced by the release can be identified and fixed before the upgrade reaches customers.
Q784. Why do you write test classes?
Test classes exercise your code so that you know how many lines are covered when execution takes place. If you want to develop robust and error-free code, test classes are the tool for testing it, and they ensure that any Apex customisation deployed to your org will operate properly.
Every test class is annotated with
@isTest- you must annotate a class with @isTest to define it as a test class.If the keyword
testMethod(or the @isTest annotation) is used on a method within a class, it is called a test method.Test classes do not count against the org's Apex code limit, and use Test.startTest()/Test.stopTest(), System.assert methods and System.runAs() for context.
Also noted:
Salesforce does not allow deployment to production if the test coverage is less than 75%. Test classes also verify that your code behaves as expected and protects it against regressions.
Q785. What is the difference between managed and unmanaged packages?
Applications installed from the AppExchange come as packages - a collection of all the elements required to make the app function correctly. The creator decides whether the package is managed or not.
Unmanaged packages - once installed, the components behave like things you created yourself in the org; they are fully editable and receive no upgrades.
Managed packages - the components are locked down from being edited, rather like apps you install on your smartphone; they live in the publisher's namespace and can be upgraded by the publisher.
Q786. What is a change set?
A change set is a collection of components that you want to migrate between related orgs - generally from a sandbox to production, but also sandbox to sandbox and other configurations. It requires a deployment connection between the orgs, and consists of an outbound change set in the source org and an inbound change set in the target org. It is similar in spirit to an AppExchange package but is used for org-to-org migration.
Q787. How can we deploy Lightning components to a production org?
We can deploy components by using managed packages, the Force.com IDE, the Force.com Migration Tool (Ant) or change sets.
Today the equivalent modern tooling is Salesforce DX with the sf project deploy start command, unlocked packages, or an unmanaged/managed package, in addition to change sets.
Q788. Can you use Salesforce Data Loader to migrate metadata?
No. Data Loader is designed for importing, exporting, updating and deleting record data. It does not handle metadata such as object schema, page layouts or Apex classes. For metadata migration, use tools such as Change Sets, the Ant Migration Tool, the Salesforce CLI/SFDX or a DevOps platform like Copado or Gearset.
Q789. How do you version control your flows, and what strategies do you use for managing changes in a development environment?
Answer supplied - source left blank.
Approach:
Salesforce's built-in versioning: each flow can have many versions, only one active at a time. Never edit an active version - "Save As New Version", test it, then activate, so rollback is simply reactivating the prior version.
Real source control: retrieve the flow metadata (force-app/main/default/flows/MyFlow.flow-meta.xml) with the Salesforce CLI and commit it to Git. Flows are XML, so they diff (imperfectly, but usefully) and can be reviewed in a pull request.
Branching strategy: feature branch per user story, developer sandboxes or scratch orgs per developer, merge into an integration branch deployed to a UAT/full sandbox, then release to production - the same pipeline as Apex, run through Azure DevOps, Copado, Gearset or Jenkins.
Naming and documentation: enforce a naming convention (Object_Trigger_Purpose), always fill in the version description explaining what changed and why, and record the story/ticket number.
Avoid merge conflicts: flows are effectively binary from a merge point of view - only one developer should edit a given flow at a time; coordinate ownership in the sprint.
Deployment: deploy flows as inactive where possible in production and activate deliberately; keep a rollback plan (the previously active version) for each release.
Q790. What is Copado?
Copado is a Salesforce-native DevOps application. It provides features such as automated deployment, version control, scheduled metadata backup, and automated regression testing. Copado can be installed in a Salesforce org and can be used to implement Agile, improve quality checks, improve collaboration, and integrate with Git. Copado offers static code analysis using PMD, SonarQube, or CodeScan.
Q791. What is a Credential in Copado?
A credential is a connection between a user and a Salesforce environment. To work with Copado, you need to create a credential with your user in the org where Copado is installed. When creating a credential, the level of access is the same as the username used to authenticate the credential.
Q792. What is a User Story in Copado?
A user story is the smallest unit of work in an Agile framework. It is an informal, general explanation of a software feature written from the perspective of the end user or customer. In Copado, a user story is also used as a container object to develop, commit, promote, and deploy development work.
Q793. What is an Environment in Copado?
An environment in Copado represents a Salesforce organization or an instance of an application in other clouds such as Heroku or MuleSoft.
Q794. What is a Commit in Copado?
A commit is the process used in Copado to link changes to a user story and record those changes in a Git repository. These committed changes are later deployed to the different environments in your pipeline, so it is essential to commit only what you need.
Q795. What is a Promotion in Copado?
A promotion is a container used to deploy one or multiple user stories from one environment to another, following a designated pipeline.
Q796. What is a Release in Copado?
A release is a feature that allows you to group user stories to promote them together, as well as to keep track of the version of changes that your application experiences after every deployment.
Q797. What is a Source Environment in Copado?
A Salesforce organization or instance of an application that carries all your changes to be promoted to the next environment. For example, if you want to promote your changes from Dev1 to UAT, Dev1 is your source environment.
Q798. What is a Destination Environment in Copado?
A Salesforce organization or instance of an application that keeps and reflects your final changes. For example, if you are promoting changes from Dev1 to UAT, UAT is your destination environment.
Q799. What is a Project in Copado?
A project is a proposed or planned undertaking of changes that are going to be made in Salesforce or other applications.
Q800. What is Copado back promotion?
Answer supplied - source left blank.
Back promotion is the process of moving changes backwards down the pipeline - from a higher environment (for example Production or UAT) into lower environments (Integration, Dev sandboxes) - so that the lower environments stay in sync with what is actually live.
It is typically used after a hotfix is applied directly to Production, or after a release is deployed, so developers are not working against stale metadata.
Copado can create back-promotion records automatically as part of the pipeline configuration, and it uses the same Git branch strategy in reverse (merging the higher branch into lower branches).
It reduces merge conflicts and prevents an older Dev environment from accidentally overwriting a production hotfix on the next forward promotion.
Q801. Which CI/CD tool do you use?
Asked at: Cognizant
Azure (Azure DevOps) is used for the CI/CD pipeline - the repository, build pipeline and release pipeline that validate and deploy the Salesforce metadata to the target orgs, usually driven by the Salesforce CLI (sfdx) and Ant/Metadata API.
Q802. Which Git commands have you used?
Asked at: Cognizant
git init - initialise a repository
git config - set user name/email and repository settings
git checkout - switch or create a branch
git status - see the working tree state
git commit - commit staged changes
Along with git clone, git add, git pull, git push and git merge in day-to-day work.
Q803. Which important file is required to deploy a community?
Asked at: Cloud 360
The Site.com / Network (site) definition - Site.com - must be included in the deployment along with the Network, CustomSite and the community's Experience Bundle metadata, otherwise the community pages will not deploy.
Q804. What is the @isTest annotation?
If you define any method as @isTest then the method is a test method. The annotation marks classes and methods that only contain code used for testing your application, and such code does not count against the organization's total Apex code limit.
Q805. How do you unit test code which has logic around the CreatedDate field?
You can create sObjects in memory with arbitrary CreatedDate values by using JSON.deserialize. This doesn't enforce the normal read-only field attributes that prevent you from setting a CreatedDate value. However, you can't commit arbitrary CreatedDate values to the database (or else it would be a serious security issue).
An example of doing so:
String caseJSON = '{"attributes":{"type":"Case","url":"/services/data/v25.0/sobjects/Case/500E0000002nH2fIAE"},'
+ '"Id":"500E0000002nH2fIAE",'
+ '"CreatedDate":"2012-10-04T17:54:26.000+0000"}';
Case c = (Case) JSON.deserialize(caseJSON, Case.class);
System.debug(c.CreatedDate);
Note that the caseJSON string was built by creating a test case and serializing it, which is the easiest way to get JSON similar to what you want; then you can just tweak the values.
Q806. How can you ignore validation rules when deploying code?
One solution uses a custom setting called ValidationRuleEnabled. All validation rules set up have && $Setup.CustomSetting__c.ValidationRuleEnabled__c added to them.
When you want to deploy any code, the administrator changes the custom setting to FALSE, deploys the new code - and must not forget to re-enable the custom setting afterwards.
This is not ideal, as the 'legacy' code should be updated to accommodate the new validation rules, ideally at the time of creating the new validation rules (but who checks code coverage after making a small change like a validation rule?).
Q807. How do you write a unit test for a trigger whose only function is to make a callout?
Both future methods and callouts can be unit tested.
To test future methods, simply make your call to any future method between Test.startTest(); and Test.stopTest(); statements, and the future method will return when Test.stopTest(); is called. See the documentation for the System.Test class.
Testing callouts is trickier. Basically, in your callout code you check to see if you're executing within a unit test context by checking Test.isRunningTest(), and instead of getting your callout response from an HttpResponse.send() request, you return a pre-built test string instead.
There is also an older approach to callout unit testing that uses a static variable you set in your unit test; just replace that static variable with a call to Test.isRunningTest() and it works fairly well too.
Q808. How do you unit test a trigger when you don't know the required fields?
Customers can have validation on custom fields via validation rules and triggers, so handling that in your unit tests without customer intervention is next to impossible.
The first step to reducing issues is to have your test data populate all standard fields and ensure the data uses the most common formatting for your customer base (US-style phone numbers and addresses for the US, for example).
Beyond that, you can use the Reflection features added to Salesforce in Summer '12 to allow customers to create unit test data classes that can be used by your managed package. Basically you define a test data generation interface and the customer creates an Apex class to generate data for you.
Using this method for unit tests run on install might be problematic, as you'd have to have the customer create the class before they install your package and your package could only look for the class by name (or iterate through all default namespace classes and check for the correct interface). However, it's no longer necessary for unit tests to run during installation for managed packages, and by default they do not.
The Reflection method requires some coding knowledge on the customer side, but you could add a tool in your application to generate the custom unit test data class for the customer.
Note: It's no longer necessary for managed package unit tests to succeed in customer orgs. They're not required on install, they will no longer prevent deployment to production, and they don't count as part of the customer's unit test coverage percentage for purposes of deployment. The only exception is if the customer uses ANT and sets the runAllTests parameter to true.
Q809. How can you delete an Apex class without an IDE?
This can be done with the Force.com Migration Tool. The tool can create or delete any metadata that can be created through the Force.com IDE or change sets. It comes with a sample config file that contains example deployments for deploying objects and Apex code, and deleting them as well. The documentation has a detailed step-by-step guide.
Q810. Is there a way to set up continuous integration for Apex tests?
It is possible, but there is no way to get true automation (i.e. set it and forget it). Common issues encountered when setting it up with Ant and Selenium:
Some features aren't supported in the Metadata API and cannot be moved via the Ant migration. If you have any unit tests that work with those features, you have to manually work on your CI org.
Deletions are harder to maintain. You have to manually update and apply a destructiveChanges.xml file or replicate the deletion in the CI org.
Some metadata XML files may have 'invalid' data in them. The suggested solution is to build a post-checkout script that manipulates the offending XML into valid XML - not ideal.
If you want to track and push out just your changes in source control (for easier rebaselining), this requires more manual maintenance of XML files (e.g. 2 new fields added on Account and you only want to push those 2 fields, not all * fields).
Conclusion: it is worth doing if you can get it set up, but if you are working on shorter-term projects and don't have a decent amount of time budgeted for it, it probably isn't worth setting up. Although it isn't CI, automated unit test execution can be set up to run every hour or so.
Q811. How do you document Salesforce.com Apex class files?
ApexDoc is the common tool used to document Apex class files. It is open source software, so you can contribute updates to it.
There is no widely successful alternative; there is an idea on the IdeaExchange for a built-in documentation generator, but it gains very little support.
Theoretically, generating docs with other tools should be fairly easy as Apex is effectively a Java DSL, so tools like Doxygen may be worth trying.
A common practical setup is to use ApexDoc to generate basic output and then a small script to copy across custom CSS and other assets.
If the IDE is open sourced, the ANTLR grammar file may become available, which would help build better documentation tooling.
Q812. What do you do when you can't deploy due to errors in third-party packages?
It was previously possible to install managed packages and ignore Apex test errors; this isn't the case anymore.
You are probably going to have to uninstall the packages if you want to deploy from sandbox to production, and then reinstall them.
If the package is available as an unmanaged version, you can work with that and fix the bugs.
If you are using the unmanaged package and don't want to uninstall before going to production, you will have to fix those errors manually by fixing the code.
Unfortunately, Salesforce test methods don't live in a complete vacuum where you can run tests against your org without bumping into other code, even when you go to deploy.
Q813. Explain Test.setCurrentPage() (Test.setPage) in Apex tests.
Asked at: Accenture
Answer supplied - source left blank.
Test.setCurrentPage(PageReference) tells the test context which Visualforce page is being "visited", so that a controller or extension under test behaves as it would on that page.
@isTest
static void testController() {
PageReference pageRef = Page.MyVfPage;
Test.setCurrentPage(pageRef);
ApexPages.currentPage().getParameters().put('id', acc.Id);
MyController ctrl = new MyController();
ctrl.save();
System.assertEquals(...);
}
It lets you set URL query-string parameters via ApexPages.currentPage().getParameters().put(...) so ApexPages.currentPage().getParameters().get('id') returns a value in the test.
Test.setCurrentPageReference() is the equivalent overload that takes a PageReference object.
Without it, ApexPages.currentPage() is null in a test and the controller throws a null pointer exception.
Q814. What is a test class?
A test class is used to test the business functionality by using some dummy data in the code. It shows the number of lines of code covered by the test. It is annotated with @isTest, does not count against the org's code limit, and by default cannot see the org's real data (unless @isTest(SeeAllData=true) is used). A minimum of 75% code coverage is needed to deploy to production.
Q815. What are the different types of sandboxes?
There are Developer, Developer Pro, Partial Copy and Full sandboxes. The difference is what data is included when the sandbox is created or refreshed:
Developer / Developer Pro - metadata only, no data initially (they differ in the amount of data/file storage they can contain: 200 MB vs 1 GB).
Partial Copy - metadata plus a sample of production data (5 GB, up to 10,000 records per object).
Full - a complete copy of production including all data.
They also differ in how often they can be refreshed: Developer daily, Partial every 5 days, Full every 29 days.
Q816. What is Apex test coverage, and what is the minimum test coverage required to deploy?
The org must have at least 75% overall Apex code coverage to deploy to production, and every trigger must have at least some test coverage.
(Note: The often-quoted "each trigger needs a minimum of 1%" is not an actual Salesforce rule. The real requirements are: 75% total coverage across the org, each trigger must have some coverage (greater than 0%), and all tests must pass. An individual class may have 0% coverage as long as the org-wide 75% is met.)
Q817. How do you identify that a class is a test class?
A test class is annotated with @isTest at the top of the class definition.
Q818. With what frequency can you refresh a full copy sandbox?
A full copy sandbox can be refreshed from production every 29 days.
Q819. What is the minimum code coverage required for every trigger for deployment?
Every trigger must have some test coverage (greater than 0%), and the overall org coverage must be at least 75%.
(Note: The commonly repeated "each trigger needs a minimum of 1%" is not an actual Salesforce rule. The deployment requirement is that each trigger has at least some coverage and the org-wide total is 75% or more.)
Q820. What is the minimum code coverage required for every class for deployment?
There is no per-class requirement. An individual class can have 0% coverage, as long as the total org-wide coverage is 75% or more.
Q821. Can you edit a Visualforce page in a production environment?
Yes, Visualforce pages can be edited directly in production.
Q822. How long can a sandbox name be?
A sandbox name can only be up to 10 characters long.
Q823. Can custom settings be accessed in a test class?
Custom setting data is not available by default in a test class. You can set the seeAllData parameter to true when defining the test class:
@isTest(seeAllData=true)
(Note: The recommended practice is to create the required custom setting records inside the test itself rather than relying on seeAllData=true, which makes tests dependent on org data.)
Q824. When a sandbox is refreshed, does the organization ID of that sandbox remain the same?
No, the organization ID changes every time the sandbox is refreshed.
Q825. Do test classes count against the Apex code limit for the organization?
No, classes marked with @isTest are not counted against the org's Apex code size limit.
Q826. What are the different ways of deploying from a sandbox to production in Salesforce?
Deployment means hosting/deploying your application into the production environment.
In the sandbox (where developers work)
Setup > Deployment Settings - the connection must allow outbound changes.
Create an outbound change set, add the components (objects, fields, classes, layouts, profiles, and so on), add dependent components and upload it to the target org.
In production
Setup > Deployment Settings - the connection must allow inbound changes.
Open Setup > Inbound Change Sets, then Validate the change set and finally Deploy it.
Points to remember:
Only metadata (objects, fields, code, configuration) is transferred by change sets - records are not. Data is moved separately with Data Loader / import and export.
Check Field Availability / profile settings so that new custom fields are not hidden after deployment.
Other options for deployment are Salesforce DX with VS Code, the Ant migration tool, scratch orgs and third-party tools such as Copado.
Also noted:
Change Sets - declarative, org-to-org deployment between related orgs.
Salesforce CLI / SFDX with metadata or source deploy into a CI/CD pipeline.
Ant Migration Tool (Force.com Migration Tool) - Java/ANT-based metadata deployment.
Unmanaged/managed packages and unlocked packages.
Third-party DevOps tools - Azure DevOps, Copado, Gearset, Jenkins, AutoRABIT, Flosum.
IDE-based deploys - VS Code with the Salesforce Extension Pack (formerly Eclipse with the Force.com IDE).
Q827. What are the best practices for writing Apex test classes?
Use the @isTest annotation at the top of every test class (and on each test method instead of the old testMethod keyword).
Always put assert statements for both positive and negative tests, for example System.assertEquals(expectedValue, actualValue).
Use a @testSetup method to create the test data once and reuse it across all test methods in the class. Only one setup method is allowed per test class.
Always use Test.startTest() and Test.stopTest() around the code under test - this gives that code a fresh set of governor limits and forces asynchronous work (future, queueable, batch) to complete. Only one pair of Test.startTest() / Test.stopTest() is allowed per method.
Use System.runAs() to test functionality in a specific user context (profile, permission set, sharing).
Do not use @isTest(SeeAllData=true) - create your own data instead; use it only for exceptional cases such as objects that cannot be created in a test (for example pricebooks in older releases).
Never hardcode Ids anywhere in a test class or an Apex class.
Make sure every class has at least 75% coverage (a trigger needs at least 1%), that the main functionality is really asserted, and push coverage as high as possible.
Test methods should be exercised with bulk data - up to 200 records - and with real-world scenarios.
Use @TestVisible to access private members from the test class.
Test.loadData() can create test data from a static resource CSV.
Custom metadata records do not need to be created in a test class (they are visible), but custom setting records must be created.
Lines that do not require coverage (braces, comments, System.debug calls) are left white in the coverage view.
Q828. Which annotations and Test methods do you use in an Apex test class and what does each do?
Annotation / method Purpose
--- ---
@isTest Marks a class or a method as a test; the code does not count against the org's code size limit.
@testSetup Creates the test data once and makes it available to all test methods of the class. Only one setup method per test class.
Test.startTest() Marks the start of the code under test and gives it a fresh set of governor limits.
Test.stopTest() Marks the end of that block and forces any queued asynchronous work to run.
@TestVisible Lets a test class access a private member (variable or method) of the class under test.
Test.loadData() Creates test records from a CSV static resource instead of writing them in code.
System.runAs() Runs a block of code as a specified user, for testing profile, permission and sharing dependent behaviour.
Test.isRunningTest() Returns true when the code is executing in a test context, so you can bypass code that must not run in a test.
Test.setMock() Registers an HttpCalloutMock / WebServiceMock implementation so callouts can be tested.
Q829. How do you cover the catch block of a try-catch in a test class?
You have to make the code actually throw the exception. The most common way is to run the method as a user whose profile does not have access to the object, field, class or method:
@IsTest
public static void getEmployeeNotificationException1() {
try {
User runUser = [SELECT Id, Name FROM User WHERE Profile.Name != 'RetailUser' LIMIT 1];
Test.startTest();
System.runAs(runUser) {
String employee = RetailUtil.getEmployeeNotification();
}
Test.stopTest();
} catch (Exception e) {
System.debug(e);
}
}
Other ways of forcing the failure path:
Insert data that violates a validation rule or a required field so the DML throws a DmlException.
Pass an invalid parameter, for example a malformed query string, and assert on the result:
@isTest
static void errorParameterTest() {
dataDeleteBatch delTest = new dataDeleteBatch('SELECT Id FROM Opportunity WHERE Name = \'errors\'', 1, '');
Database.executeBatch(delTest);
System.assertEquals(0, [SELECT COUNT() FROM Opportunity WHERE Name = 'Error']);
}
Write a separate test method for the else/failure branch of every condition, because one method can only take one path through an if.
Q830. The execute() method of your batch class is not being covered by the test class. How do you fix it?
Remember that in a test context the execute() method is called only once (all the records in scope are processed in a single chunk between Test.startTest() and Test.stopTest()), so the test data must be created before the batch is launched.
Make sure the start() method's query actually returns the records that execute() is supposed to process - if the query returns nothing, execute() never runs. Create records that match the query filters exactly, and remember not to rely on org data.
Create/update the fields that the execute() method filters on before calling Database.executeBatch().
Call the batch inside Test.startTest() / Test.stopTest() so that the job completes before the assertions run.
If you have chained batch classes, write a separate test method for each batch class rather than relying on the chain to run.
Add asserts on the records after Test.stopTest() to prove the processing happened.
Q831. How do you handle multiple API callouts in a test class?
A test method cannot make real callouts, so you register a mock with Test.setMock(HttpCalloutMock.class, new MyMock()). The mock class implements the HttpCalloutMock interface and provides public HTTPResponse respond(HTTPRequest req), which receives the request and returns the response you want.
When there are several different callouts, inspect the request inside the single mock and branch on the endpoint (or on the method/body) with an if / else if block, returning a different HttpResponse body and status code for each endpoint.
Alternatively use Test.setMock with a MultiStaticResourceCalloutMock, which maps each endpoint to a different static resource holding the JSON response.
Where the code cannot be mocked, guard it so the callout is skipped in a test and a hardcoded response is used instead:
if (!Test.isRunningTest()) {
res = http.send(req);
} else {
res = '{"BookingCode": "' + td.External_Id__c + '", "OTP": "' + td.Feedback__r.OTP__c + '"}';
}
Q832. How do you test Apex code that makes a callout?
Apex test methods don't support callouts - a real callout in a test throws an exception.
A mock callout lets you specify the response to return in the test instead of calling the web service.
Create a class that implements the HttpCalloutMock interface and returns a canned HttpResponse from its respond() method.
In the test, register it before calling the code under test: Test.setMock(HttpCalloutMock.class, new AnimalsHttpCalloutMock());
For SOAP stubs, implement WebServiceMock and register it with Test.setMock(WebServiceMock.class, new MyWebServiceMock());
StaticResourceCalloutMock and MultiStaticResourceCalloutMock let you hold the response body in a static resource instead of in code.
Remember that when you call out from a method, the method waits for the external service to respond before executing subsequent lines. To avoid blocking, place the callout in an asynchronous method annotated with @future(callout=true) or use Queueable Apex, so the callout runs on a separate thread.
Q833. Write a test class for a Batch Apex job that updates contact addresses.
@isTest
private class UpdateContactAddressesTest {
@testSetup
static void setup() {
List<Account> accounts = new List<Account>();
List<Contact> contacts = new List<Contact>();
// insert 10 accounts
for (Integer i = 0; i < 10; i++) {
accounts.add(new Account(Name = 'Account ' + i,
BillingCity = 'New York',
BillingCountry = 'USA'));
}
insert accounts;
// find the accounts just inserted, add a contact for each
for (Account account : [SELECT Id FROM Account]) {
contacts.add(new Contact(FirstName = 'first',
LastName = 'last',
AccountId = account.Id));
}
insert contacts;
}
static testMethod void test() {
Test.startTest();
UpdateContactAddresses uca = new UpdateContactAddresses();
Id batchId = Database.executeBatch(uca);
Test.stopTest();
// after the testing stops, assert records were updated properly
System.assertEquals(10, [SELECT COUNT() FROM Contact WHERE MailingCity = 'New York']);
}
}
The batch is executed between Test.startTest() and Test.stopTest(); the asynchronous job runs synchronously at Test.stopTest(), so the assertions afterwards see the results. Only one batch execution can be tested this way, and @testSetup creates the data once for all test methods.
Q834. What are the steps for deploying code from a sandbox to production using change sets?
1. In the sandbox, create an Outbound Change Set and add all the classes, triggers and test classes. Include the test classes that are already deployed too, because they help the overall test run pass.
2. Upload the change set to the target org.
3. In production, open the Inbound Change Set.
4. Take a backup of the files that will be modified.
5. Validate first, supplying a comma-separated list of the test classes to run.
6. If the validation passes, deploy (a quick deploy is possible within the validation window).
Change sets only move metadata between orgs connected by a deployment connection; for anything more repeatable use the Metadata API, SFDX / sf project deploy, or a CI tool with a version-control repository.
Q835. What is DevOps, and what makes setting up DevOps for Salesforce different?
DevOps is the blending of tasks performed by a company's application development and systems operation teams.
Differences when setting up DevOps with Salesforce:
1. Salesforce does not maintain versions of the configuration or code, so it has to be kept in a version-control repository outside Salesforce.
2. Salesforce has multiple development and deployment models - change sets, org development, and package development - and you must choose one.
3. Salesforce comes with multiple sandbox environments, and they must be set up correctly to enable an efficient path to production.
4. Check points and quality gates are needed to ensure the quality of the solution being promoted to higher environments.
5. There are testing requirements (minimum code coverage, running tests) for deployment to production and to intermediate test stages.
Scenario-Based Questions
20 questions
Q836. Let's say I have 150 batch jobs to execute. Will I be able to queue them in one go?
Once you run Database.executeBatch, the batch jobs will be placed in the Apex Flex queue and their status becomes Holding. The Apex Flex queue has a maximum of 100 jobs; beyond that, Database.executeBatch throws a LimitException and doesn't add the job to the queue. So at most 100 jobs can be added in one go.
Also, if the Apex Flex queue is not enabled, the job status becomes Queued. Since the concurrent limit of queued or active batches is 5, at most 5 batch jobs can be added in one go.
Q837. Let's say Record A has to be processed before Record B, but Record B came in the first batch and Record A came in the second batch. The batch picks up records that are unprocessed every time it runs. How will you control the processing order?
The processing order can't be controlled, but we can bypass the processing of Record B before Record A. We can implement Database.Stateful and use one class variable to track whether Record A has been processed or not. If it is not processed and Record B has come, don't process Record B. After all the execution completes, Record A has already been processed, so run the batch again to process Record B.
Q838. Let's say we have run an Apex batch to process 1000 records with a batch size of 200. Now, while doing DML on the 395th record, an error occurred. What will happen in that case?
In batches, if the first transaction succeeds but the second fails, the database updates made in the first transaction are not rolled back.
Since the batch size is 200, the first batch will be processed completely and all data will be committed to the database. In the second batch, if we are committing records using normal DML statements like insert or update, then the whole batch will be rolled back. So records 201 to 400 will not be processed.
Q839. Suppose I create two accounts a1 and a2 and make a2 the parent of a1. What happens if I then try to make a1 the parent of a2?
Salesforce does not allow it. A record cannot be both the parent and the child in the same hierarchy - creating that circular reference produces an error ("Invalid Data - a record cannot be its own parent / circular reference"). Once a record is designated as the master (parent) in the relationship chain, you cannot flip the direction so that its own child becomes its parent.
Q840. Suppose there is a custom field with a default value that is not added to the page layout. If you clone a record from the UI, what will the value of that field be in the new record?
The new record gets the default value defined at the field level, not the value that was populated on the record being cloned. Because the field is not on the layout, the clone operation cannot carry the source value forward, so the field default is applied instead.
Q841. You have created a custom object, but while creating a report you cannot select the object in the report builder. What could be the issue?
Check whether the Allow Reports checkbox is enabled on the custom object's detail page in Object Manager. Without it, no report type - standard or custom - is available for that object.
Q842. You are not getting an option to create list custom settings. Which setting needs to be enabled?
Go to Setup > Schema Settings and enable Manage List Custom Settings Type. Once enabled, the List type option appears when creating a custom setting.
Q843. You are trying to convert a master-detail relationship field to a lookup relationship, but the Change Field Type button is not visible. What could be the reason?
There must be no roll-up summary field present on the parent object that rolls up the child object. Additionally, if a deleted roll-up summary field is still sitting in the Recycle Bin, it must be erased permanently before the conversion is allowed. Other blockers include the child having more than the allowed number of master-detail relationships, or detail records existing where the lookup would need to be optional.
Q844. One of the users in your org is not able to create campaigns, even though the profile and permission sets grant access to create campaigns. What could be the reason?
Check whether the Marketing User checkbox is selected on that user's detail record. Without the Marketing User flag, a user cannot create or edit campaigns (or use the campaign import wizards), regardless of object permissions.
Q845. You have written an LWC that uses the @wire decorator to get data from Apex, but no data comes back and the Apex code looks fine. What could be one of the reasons?
Check whether the Apex method is annotated with @AuraEnabled(cacheable=true). A method wired with @wire must be cacheable; without cacheable=true alongside the @AuraEnabled annotation, the wire adapter cannot call it and no data is returned. (The method must also be static and public/global.)
Q846. Can you explain a situation where you used Salesforce Flow to solve a complex business problem?
Answer supplied - source left blank.
Answer with a STAR-format real example. A strong model answer:
Situation: The service team manually created renewal opportunities and follow-up tasks whenever a support entitlement was within 60 days of expiry - a daily spreadsheet exercise that was error-prone and often missed accounts.
Task: Automate the whole renewal creation and notification chain without adding Apex, so the business could own the rules.
Action: Built a schedule-triggered flow running nightly over Entitlements expiring in 60 days. It used a Get Records to pull the related Account and Contract, a Decision to branch on contract value (high-value accounts route to a named account manager, others to a queue), a Create Records for the renewal Opportunity and Tasks, and an Assignment to build collections so all DML happened outside the loop. Fault paths logged failures to a custom Integration_Log__c object and emailed the admin. A screen flow on the Opportunity let reps confirm or decline the renewal, updating the record and posting to Chatter.
Result: Eliminated about 10 hours of manual work each week, renewals were no longer missed, and renewal pipeline coverage rose measurably. Because it was declarative, the ops team could later change the 60-day threshold themselves.
Q847. How do you create a master-detail relationship on an object that already contains records?
No, we cannot directly create a master-detail relationship if the custom object contains existing records.
Following are the steps to create a master-detail relationship when records are available in a custom object:
1. First create the field with a lookup relationship.
2. Then associate the lookup field with a parent record for every record.
3. Next, change the data type of the field from lookup to master-detail.
Q848. A record meets the criteria of a time-based workflow rule and the action is placed in the queue. Before the time-based action fires, the record is modified so that it no longer meets the workflow criteria. What happens to the queued time-based action?
The time-based workflow action is removed from the queue and will not fire.
Q849. How do you add a related record from a trigger?
Do it in an after trigger, because the parent record's Id is only available after the record is saved. Build the child records in a list while looping over Trigger.new and issue a single DML statement outside the loop so the code stays bulkified.
trigger AccountTrigger on Account (after insert) {
List<Opportunity> oppsToInsert = new List<Opportunity>();
for (Account acc : Trigger.new) {
oppsToInsert.add(new Opportunity(
Name = acc.Name + ' - Opportunity',
AccountId = acc.Id, // relate the child to the parent
StageName = 'Prospecting',
CloseDate = System.today().addDays(30)
));
}
if (!oppsToInsert.isEmpty()) {
insert oppsToInsert;
}
}
Key points:
Use after insert / after update, never before insert (no Id yet).
Never put the DML inside the for loop.
Move the body into a helper class and keep one trigger per object.
Q850. Write a trigger so that whenever an Account is added, a related Opportunity is created automatically.
trigger CreateRelatedOpportunity on Account (after insert) {
AccountTriggerHandler.createOpportunities(Trigger.new);
}
public with sharing class AccountTriggerHandler {
public static void createOpportunities(List<Account> newAccounts) {
List<Opportunity> opps = new List<Opportunity>();
for (Account acc : newAccounts) {
opps.add(new Opportunity(
Name = acc.Name + ' - New Business',
AccountId = acc.Id,
StageName = 'Prospecting',
CloseDate = System.today().addDays(30)
));
}
if (!opps.isEmpty()) {
insert opps;
}
}
}
The trigger must be an after insert trigger so that acc.Id is populated.
The Opportunity records are collected in a list and inserted with a single DML statement outside the loop, so the trigger works for 1 or 200 accounts.
Q851. Write a trigger to create a new related Contract whenever an Opportunity is Closed Won.
trigger OpportunityTrigger on Opportunity (after insert, after update) {
OpportunityTriggerHandler.createContracts(Trigger.new, Trigger.oldMap);
}
public with sharing class OpportunityTriggerHandler {
public static void createContracts(List<Opportunity> newOpps, Map<Id, Opportunity> oldMap) {
List<Contract> contracts = new List<Contract>();
for (Opportunity opp : newOpps) {
Boolean wasWon = oldMap != null
&& oldMap.containsKey(opp.Id)
&& oldMap.get(opp.Id).StageName == 'Closed Won';
// fire only when the stage has just changed to Closed Won
if (opp.StageName == 'Closed Won' && !wasWon && opp.AccountId != null) {
contracts.add(new Contract(
AccountId = opp.AccountId,
Status = 'Draft',
StartDate = System.today(),
ContractTerm = 12,
Opportunity_Name__c = opp.Id // custom lookback field to the opportunity
));
}
}
if (!contracts.isEmpty()) {
insert contracts;
}
}
}
Points to mention in an interview:
Use an after trigger so the Opportunity Id and AccountId are available.
Compare against Trigger.oldMap so the contract is created only on the transition into Closed Won, not on every later edit of a won opportunity.
A Contract requires an AccountId and a Status, so skip opportunities with no account.
Collect and insert in bulk, outside the loop.
Q852. How would you show how many days an Opportunity has been sitting in its current stage, without writing code?
Declarative options:
Enable field history tracking on the Opportunity Stage field and report on the Opportunity Field History report type, which gives the date each stage change happened.
Salesforce provides a standard set of fields for exactly this on Opportunity: Last Stage Change Date and Stage Duration (available once "Opportunity Stage Change Fields" / Opportunity Update Reminders are enabled), which can be dropped straight on the layout and used in reports.
If those are not available, create a date field ("Stage Changed Date") updated by a workflow field update or a Process Builder / Flow whenever the Stage changes, and then a formula field TODAY() - Stage_Changed_Date__c that returns the number of days in the current stage.
Colour it with conditional highlighting on a report or a Path with key fields so that sales users can see stale deals at a glance.
Q853. Write a trigger that assigns newly created records to the members of a queue in round-robin fashion.
First create the queue and add the users to it, then write an after insert trigger that reads the queue members and picks an owner using the modulus of a running number.
trigger RoundRobinMSalary on max_salary__c (after insert) {
public static Boolean runOnce = false;
public static Boolean runMerge = false;
List<max_salary__c> ticketList = [SELECT Id, OwnerId, msal__c
FROM max_salary__c
WHERE Id IN :Trigger.NewMap.keySet()];
Integer index;
Integer ticketNumber;
Integer agentSize;
List<User> agentList = new List<User>();
Set<Id> userIdsSet = new Set<Id>();
for (GroupMember gm : [SELECT Id, UserOrGroupId FROM GroupMember
WHERE GroupId IN (SELECT Id FROM Group
WHERE Type = 'Queue' AND Name = '4UserQueue')]) {
userIdsSet.add(gm.UserOrGroupId);
}
System.debug('#### userIdsSet = ' + userIdsSet);
agentList = [SELECT Id, Name, Profile.Name FROM User
WHERE Id IN :userIdsSet AND IsActive = true];
if (agentList == null || agentList.size() == 0) return;
System.debug('#### agentList = ' + agentList);
for (max_salary__c c : ticketList) {
if (c.msal__c != null) {
ticketNumber = Integer.valueOf(c.msal__c);
agentSize = agentList.size();
index = Math.mod(ticketNumber, agentSize);
System.debug('#### index = ' + index);
c.OwnerId = agentList[index].Id;
}
}
if (ticketList != null && ticketList.size() > 0) {
System.debug('#### Updating tickets = ' + ticketList);
update ticketList;
}
}
The queue members are read from GroupMember where the group Type = 'Queue', inactive users are filtered out, and Math.mod(number, agentSize) cycles the index through the list of agents. Because ownership can only be set after the record has an Id, the trigger runs after insert and issues an explicit update.
Q854. How would you implement round-robin assignment where the last assigned index is remembered between transactions?
Store the pointer in a hierarchy custom setting so the rotation continues across separate transactions instead of depending on a field on the record.
trigger RoundRobinMSalary on max_salary__c (after insert) {
List<max_salary__c> ticketList = [SELECT Id, OwnerId, msal__c
FROM max_salary__c
WHERE Id IN :Trigger.NewMap.keySet()];
Integer index;
Integer agentSize;
List<User> agentList = new List<User>();
Set<Id> userIdsSet = new Set<Id>();
for (GroupMember gm : [SELECT Id, UserOrGroupId FROM GroupMember
WHERE GroupId IN (SELECT Id FROM Group
WHERE Type = 'Queue' AND Name = '4UserQueue')]) {
userIdsSet.add(gm.UserOrGroupId);
}
agentList = [SELECT Id, Name, Profile.Name FROM User
WHERE Id IN :userIdsSet AND IsActive = true];
if (agentList == null || agentList.size() == 0) return;
MSal_Round_Robin_Assignment__c msc = MSal_Round_Robin_Assignment__c.getOrgDefaults();
Integer userIndex = (msc.get('User_Index__c') == null || Integer.valueOf(msc.get('User_Index__c')) < 0)
? 0 : Integer.valueOf(msc.get('User_Index__c'));
for (max_salary__c c : ticketList) {
agentSize = agentList.size();
index = (userIndex + 1) >= agentSize ? 0 : userIndex + 1;
c.OwnerId = agentList[index].Id;
userIndex = index;
}
msc.User_Index__c = userIndex;
if (ticketList != null && ticketList.size() > 0) {
update ticketList;
update msc;
}
}
The custom setting MSal_Round_Robin_Assignment__c holds User_Index__c, the index of the last user assigned. It is read with getOrgDefaults(), advanced once per record in the batch, and written back at the end - a single DML for the setting no matter how many records were inserted.
Q855. How do you make two API callouts from a single Batch Apex job?
Answer supplied - source left blank.
Batch Apex allows callouts as long as the class declares Database.AllowsCallouts, and each of start, execute and finish may make up to 100 callouts. To make two calls per batch, put both calls behind one service class and invoke them in sequence from execute, keeping the scope size small (for example 1-10 records) so you stay inside the callout and CPU limits.
global class TwoCalloutBatch implements Database.Batchable<sObject>, Database.AllowsCallouts, Database.Stateful {
global Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id, Name, External_Id__c FROM Account WHERE Sync__c = true');
}
global void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
// First API - fetch enrichment data
HttpResponse first = IntegrationService.call('GET', '/enrich/' + a.External_Id__c, null);
if (first.getStatusCode() == 200) {
// Second API - push the enriched record onward
IntegrationService.call('POST', '/sync', first.getBody());
}
}
}
global void finish(Database.BatchableContext bc) {
}
}
// Run it with a small scope so the callout limit per transaction is not exceeded
Database.executeBatch(new TwoCalloutBatch(), 10);
Using an interface or an abstract service class (IntegrationService) for the callout is the object-oriented way to keep the two calls interchangeable and easy to mock in tests - the test registers a Test.setMock(HttpCalloutMock.class, ...) implementation that returns a canned response for each endpoint. If the second call depends on the first completing asynchronously, chain a Queueable from finish() instead.
SSIA :
Q. What are the SF integration fundamentals ?
REST API
SOAP API
JSON
XML
HTTP Methods
GET
POST
PUT
PATCH
DELETE
Q. What are the Salesforce APIs ?
REST API
SOAP API
Bulk API – Asynchronous Api, large volume of millions data processing to external system like SAP.
Metadata API – works with SF components/configurations. LWC, Objects, Fields, Apex, Flows etc.
Tooling API – development tool which provides access to Apex classes, triggers, code coverage, debug logs, LWC etc.
Composite API - combine multiple REST API requests into a single HTTP call. Helps reduce API limits, improves performance. like creation of Accounts, Contacts, and Opportunities in a single transaction. https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_composite_composite_post.htm
GraphQL API - allows clients to request exactly the data they need from Salesforce in a single query, instead of making multiple REST API calls. developed by Facebook and supported by Salesforce through the UI API-based GraphQL endpoint. https://developer.salesforce.com/docs/platform/lwc/guide/reference-graphql.html
Need to create/update a few records?
→ REST API
Need to create multiple related records together?
→ Composite API
Need to load/retrieve millions of records?
→ Bulk API
Need to deploy Apex, LWC, Flows?
→ Metadata API
Need to run tests, coverage, logs?
→ Tooling API
Need to fetch complex related data efficiently?
→ GraphQL API
API
Best Use Case
REST API
Simple CRUD operations
Composite API
Multiple operations in one request
GraphQL API
Efficient data retrieval
Bulk API
Large volume processing
Metadata API
Deployment and metadata migration
Tooling API
Testing, debugging, code coverage
Q. What are the Salesforce Authentication & Security ?
OAuth 2.0 – authorize without using Username and Password.
• Client Credentials Flow : Client ID + Client Secret + Access Token.
• JWT Bearer Flow : Signed JWT token is used instead of password.
• Web Server Flow : User Login > Salesforce > Authorization code > Access Token.(VSCode org authentication)
Certificates
• Self Signed : generated internally for Sandbox development.
• CA Signed : trusted Certificate, used in PROD for 3rd party sharing trust like SAP.
Security
• Named Credentials : securely store Endpoint URL and credentials.
• Mutual TLS : two ways authentication Client SF ßà Server SAP, both need to authenticate trust.
• Encryption : Data encrypted while storing.
JWT Authentication Benefits:
• No password storage
• Certificate trust
• Secure integration
Q. What are the Real-Time Integrations ?
==Integration Patterns:
1. Request-Reply (Salesforce > Request > SAP > Response)
2. Fire-and-Forget (Salesforce > Send Order > SAP) no waiting for response.
Q. Examples of Integration patterns. ?
Requirement
Recommended Pattern
Real-time customer lookup
Request-Reply(SF ß à SAP)
SAP creates records in Salesforce
Remote Call-In(SAP to SF – REST, SOAP, Composite)
Salesforce invokes SAP process
Remote Process Invocation (SF à REST à SAP)
Large volume data load
Batch / Bulk API
Real-time notifications
Platform Events
Account sync across systems
CDC
Documents transfer
File Transfer (SF à Azure Blob à SAP)
Multiple Salesforce operations
Composite API
Enterprise architecture
API-Led Connectivity(reusable code à Expreince API à Process API à System API à Salesforce + SAP)
Real-time + periodic sync
Hybrid Pattern (night Batch job runs schedule)
Q. What are the Middleware Architecture ?
1. MuleSoft
2. SAP CPI
3. Azure Logic Apps
4. Boomi
5. Informatica
Q. Why Middleware?
========== Without Middleware
Salesforce → SAP
Salesforce → Dealer System
Salesforce → E-Sign
Salesforce → ERP
Salesforce → Finance
Many point-to-point integrations.
========With Middleware
SAP
↑
Salesforce → MuleSoft
↓
Dealer System
↓
E-Sign
Single integration hub.
Q. What is Event Driven Architecture ?
SF > Publish Event > Event Bus > (SAP, MULESOFT etc)
1. Platform Events : SF native event messaging framework.
2. CDC (Change Data Capture) : automatically publish event whenever a record gets changed, do not write Apex. Create, Update, Delete, Undelete.
3. Event Bus : messaging infrastructure that stores and distributes events.
4. Pub/Sub API : High-performance API that allows external systems to publish and subscribe to Salesforce events using gRPC.
Q. What is Enterprise Integration Patterns ?
Standard integration blueprints that architects use to solve system-to-system communication problems.
1. Batch Processing : transfers data in bulk at scheduled intervals rather than immediately.
2. Queue Based : stores messages in a queue until a consumer processes them.
3. Publish Subscribe : published once and delivered to multiple subscribers in real time.
Q. What is Integration Architect Level ?
designing the entire integration ecosystem across Salesforce, SAP, MuleSoft, Azure, Data Lake, Dealer Portal, Mobile Apps, and external systems.
1. System Landscape Design : Which systems exist, how they interact, what integration patterns are used, and where middleware should be introduced.
2. Scalability : Load Balancing, Ability of a system to handle increasing users, transactions, and data volumes without performance degradation.
3. API Management : managing entire Lifecycle of Apis.
4. Monitoring : continuous observation, transactions count, failed transactions.
5. Fault Handling : how failures are handled. Solution retry – error handling – error logs.
6. Retry Mechanisms : auto reprocessing failed transactions.
7. Data Governance : Ensuring data quality, ownership, security, compliance, and consistency across enterprise systems.
An Integration Architect designs:
Who talks to whom?
Which APIs are exposed?
Synchronous or Asynchronous?
What happens if SAP is down?
How are failures handled?
How is monitoring performed?
Architect Focus
Daily transaction volume
Peak traffic
Future growth
API limits
Platform limits
Architect Goal
Detect issues before users complain.
Q. What is Delta Records in syncing the records from Salesforce to SAP Price Master vice versa ?
Only the changed records gets exchanged between systems instead of sending all records every time. Using the Last modified date identify.
Scenarios Every Salesforce Architect Should Know
1. Salesforce ↔ SAP Product Master
• Bulk API
• Middleware
• Scheduled Sync
2. Salesforce ↔ SAP Price Master
• Batch Processing
• Delta Records
3. Salesforce ↔ E-Sign
• Real-Time REST API
• Callback/Webhook
Interview Questions and Answers
1. What factors do you consider before selecting an integration pattern?
Answer:
As an Integration Architect, I evaluate:
Business requirement (real-time or batch)
Data volume
Performance requirements
Error handling requirements
System availability
Security requirements
API limits
Future scalability
Example
Customer Credit Check
User creates Order in Salesforce
Salesforce sends request to SAP
SAP returns credit status immediately
Pattern: Request-Reply (Synchronous)
Product Master Sync
Millions of products
Nightly synchronization
Pattern: Batch Processing using Bulk API
2. How do you decide between REST API and SOAP API?
Answer:
REST API
Preferred when:
Lightweight
JSON format
Mobile applications
Web applications
Modern integrations
SOAP API
Preferred when:
Strict contract required
WSDL-based development
Enterprise systems
Strong security standards
Example
SAP ECC often uses SOAP services.
Modern SAP S/4HANA integrations generally use REST APIs.
3. Explain a real SAP-Salesforce integration you designed.
Answer:
Scenario
Dealer creates Vehicle Order in Salesforce.
Flow
Salesforce ↓ MuleSoft ↓ SAP
Steps
User submits order
Salesforce publishes Platform Event
MuleSoft consumes event
MuleSoft transforms payload
SAP creates Sales Order
SAP returns Order Number
MuleSoft updates Salesforce
Benefits
Loose coupling
Scalable
Reliable
Retry capability
4. When would you use Platform Events instead of REST API?
REST API
Use when immediate response is required.
Example:
Price Check
Inventory Check
Customer Verification
Platform Events
Use when immediate response is not required.
Example:
Order Created
Warranty Created
Dealer Notification
Architect Perspective
Request-Reply = User waiting
Platform Event = Event-driven architecture
5. Explain Salesforce API limits and how you manage them.
Answer
Salesforce has API request limits.
To reduce limit consumption:
Use Composite API
Instead of:
10 REST calls
Use:
1 Composite API call
Use Bulk API
Instead of:
100,000 REST calls
Use:
1 Bulk Job
Use Platform Events
Avoid continuous polling.
Use Middleware Caching
Frequently requested data can be cached in MuleSoft.
6. What is API-Led Connectivity?
Answer
MuleSoft architecture consists of:
System API
Connects to backend systems.
Examples:
SAP
Oracle
Mainframe
Process API
Business logic layer.
Examples:
Product Pricing
Customer Eligibility
Experience API
Consumer-specific APIs.
Examples:
Salesforce API
Mobile API
Dealer Portal API
Diagram
Salesforce
|
Experience API
|
Process API
|
System API
|
SAP
Benefits:
Reusability
Scalability
Reduced duplication
7. What happens when SAP is down?
Answer
Architectural best practices:
Option 1
Queue Message
Salesforce
↓
Queue/Event
↓
SAP
Message waits until SAP is available.
Option 2
Retry Mechanism
Retries:
5 mins
15 mins
30 mins
Option 3
Dead Letter Queue
Failed transactions stored for investigation.
Option 4
Alerting
Email/Slack/ServiceNow notification.
8. What are Delta Records?
Answer
Only changed records are synchronized.
Example
Product Table:
Product
Modified
A
No
B
Yes
C
No
Only Product B gets transferred.
Benefits
Reduced API calls
Faster processing
Less network traffic
Implementation
Using:
LastModifiedDate
SystemModstamp
CDC Events
9. Difference between Platform Events and CDC?
Platform Events
Custom event
Business-driven
Developer publishes event
Example:
Order Created
Vehicle Delivered
Warranty Registered
CDC
Record-driven
Automatic publishing
No custom Apex required
Example:
Account Updated
Product Updated
Price Updated
Interview Statement
Platform Events are business events, while CDC captures data changes automatically.
10. How do you secure Salesforce integrations?
Answer
Authentication
OAuth 2.0
JWT Bearer Flow
Client Credentials Flow
Credentials Storage
Named Credentials
External Credentials
Transport Security
HTTPS
TLS 1.2+
Mutual Authentication
Mutual TLS
Data Security
Shield Encryption
Field Level Security
Monitoring
Event Monitoring
Audit Logs
11. Why use JWT Authentication?
Answer
JWT is preferred for server-to-server integrations.
Process
SAP
↓
Signed JWT
↓
Salesforce
↓
Access Token
↓
API Access
Benefits:
No password storage
Certificate-based authentication
Highly secure
Automated
Used extensively in:
SAP
MuleSoft
Azure
Enterprise integrations
12. Difference between Bulk API 1.0 and 2.0?
Bulk API 1.0
Multiple batches
Complex processing
Manual batching
Bulk API 2.0
Salesforce handles batching
Simpler implementation
Better performance
Architect Recommendation
Use Bulk API 2.0 for new implementations.
13. How would you integrate Salesforce with SAP Price Master?
Answer
Challenge
Millions of pricing records.
Solution
SAP Price Master
↓
Middleware
↓
Bulk API
↓
Salesforce
Design
Delta records only
Scheduled job
Bulk API
Error queue
Monitoring dashboard
Result
Faster sync
Lower API consumption
Better scalability
14. How do you monitor integrations?
Answer
Monitoring should exist at multiple levels:
Salesforce
Apex Jobs
Platform Events
Event Monitoring
Debug Logs
Middleware
MuleSoft Monitoring
SAP CPI Monitoring
Enterprise
Splunk
Azure Monitor
Datadog
Metrics:
Success rate
Failure rate
Average response time
Queue depth
Daily transaction count
15. What are the key responsibilities of a Salesforce Integration Architect?
Answer
An Integration Architect is responsible for:
System Landscape Design
API Strategy
Security Architecture
Middleware Design
Event-Driven Architecture
Monitoring Strategy
Error Handling
Scalability Planning
Data Governance
DevOps & Deployment Strategy
Key Interview Closing Statement
"As a Salesforce Integration Architect, my role is not only to connect systems but to design a secure, scalable, resilient, and reusable enterprise integration ecosystem across Salesforce, SAP, MuleSoft, Azure, and other enterprise applications while ensuring business continuity, performance, and governance."
Q. Salesforce Einstein AI ?
A. Salesforce introduced Einstein as a predictive AI platform in 2016, offering features like Lead Scoring and Opportunity Forecasting. It later expanded with Einstein Generative AI and now includes Agentforce, enabling AI agents that can reason, plan, and execute tasks across Salesforce workflows.
using Large Language Models (LLMs):
Email drafts
Case summaries
Knowledge articles
Sales call summaries
Marketing content
Practical examples of Integrations ?
Q. Example of Composite API ?
A. All subrequests are executed in the context of the same user. In a subrequest’s body, you specify a reference ID that maps to the subrequest’s response.
{
"compositeRequest" : [{
"method" : "POST",
"url" : "/services/data/v67.0/sobjects/Account",
"referenceId" : "refAccount",
"body" : { "Name" : "Sample Account" }
},{
"method" : "POST",
"url" : "/services/data/v67.0/sobjects/Contact",
"referenceId" : "refContact",
"body" : {
"LastName" : "Sample Contact",
"AccountId" : "@{refAccount.id}"
}
}]
}
Q. Example of GraphQL API ?
A. using Lightning Data Service (LDS)
// simpleAccounts.js
import { LightningElement, wire } from "lwc";
import { gql, graphql } from "lightning/uiGraphQLApi";
export default class SimpleGQL extends LightningElement {
results;
errors;
@wire(graphql, {
query: gql`
query AccountWithName {
uiapi {
query {
Account(first: 10) {
edges {
node {
Id
Name {
value
}
}
}
}
}
}
}
`,
})
graphqlQueryResult({ data, errors }) {
if (data) {
this.results = data.uiapi.query.Account.edges.map((edge) => edge.node);
}
this.errors = errors;
}
}
Q. What is Web Server Flow : Access Token ?
A. it must the user manual human interaction to login not recommended for backend to backend connection SAP to SF.
Q. what is Mutual TLS in salesforce and how to use it. ?
A. both the client and the server authenticate required.
Client ß à Salesforce
Verify Server ß Access Token shraed verify à Verify Client
Certificate ß client certificate and key shared to verify certificate àCertificate
No username/password
No manual login
Certificate-based trust
Highly secure
Q. Salesforce How to Encryption data while storing. ?
A. from Setup > Platform Encryption + Setup > Key Management > Generate Tenant Secret + Setup > Encryption Policy. (it mask the standard and custom fields like credit card numbers etc)
Blob data = Blob.valueOf('Sensitive Data');
Blob encrypted = Crypto.encryptWithManagedIV(
'AES256',
Crypto.generateAesKey(256),
data
);
Q. Salesforce Platform Events Example ?
A. process of Publish and Subscribe events from SAP Publish and SF multiple Subscribe. Event-Driven messaging framework that enables asynchronous communication between Salesforce and external systems using a publish-subscribe model.
Setup → Platform Events → New Platform Event
SF Publish > SAP Subscribe :
Create Platform Event - Quote_Approved__e
Fields - Quote_Number__c
Account_Number__c
Amount__c
Status__c
Apex Example :
public class QuoteService {
public static void publishQuoteEvent(Id quoteId){
Quote q = [ SELECT Id,Name,GrandTotal,Status FROM Quote WHERE Id = :quoteId];
Quote_Approved__e eventMsg = new Quote_Approved__e(
Quote_Number__c = q.Name,
Amount__c = q.GrandTotal,
Status__c = q.Status
);
EventBus.publish(eventMsg);
}
}
SAP Subscribe at URL : /event/Quote_Approved__e
With payload of data passed in JSON format data received by SAP.
Q. Whats the difference between Platform Event and Pub/Sub API ?
A.
Item
Platform Event
Pub/Sub API
What is it?
Event Object
API
Purpose
Store/Event Message
Publish & Subscribe
Salesforce Object
Yes
No
Custom Payload
Yes
Reads payload
SAP Integration
Consumes Event
Connects to Event
CDC Support
No
Yes
Q. Credentials Storage
• Named Credentials : encrypted Username and Password storing.
• External Credentials :
Authentication Protocol
OAuth 2.0
Client ID
Client Secret
JWT Config
Certificate
Identity Type
Q. salesforce what the mean of Flow & Flow Orchestration ?
A. Flow – Autolaunched process:
Flow Type
Purpose
Record-Triggered Flow
Runs when a record is created, updated, or deleted
Screen Flow
User interacts through screens
Scheduled Flow
Runs at a specific time
Autolaunched Flow
Runs in background without UI
Platform Event Flow
Runs when an event is received
Flow Orchestration is used to coordinate multiple flows, users, and approval processes across a larger business process.
Setup → Flow → New Flow → Flow Orchestration
Q. What is Agile Methodology?
A. Daily Standup call > Sprints Meetings > Sprints Plan > Sprint Release > New Sprint
Roles > Product Owner (Requirement Define) > Scrum Master(Agile Process ) > Development Team (developers, testing)
Q. What is DataWeave ?
A. Transform data between different formats:
XML to JSON etc.
Q. What is SonarQube ?
A. SonarQube is a static code analysis platform that continuously inspects source code for bugs, vulnerabilities, code smells, duplication, and coverage issues. It helps development teams maintain high code quality by enforcing quality gates and integrating with CI/CD pipelines.
Q. What is Jira ?
A. project management and issue tracking tool developed by Atlassian.
Eg: Requirements, User Stories, Bugs, Tasks, Sprints, Releases.
Salesforce Fundamentals & Platform Concepts
35 questions
Q856. How many Salesforce clouds are there and what is their flow? Explain Experience Cloud, Partner Community, Sales Cloud and Service Cloud.
Answer supplied - source left blank.
get Answer from SSIA doc.
Salesforce ships several product clouds on the same core platform:
Sales Cloud - manages the selling process. Typical flow: Campaign > Lead > Lead qualification > Convert to Account/Contact/Opportunity > Opportunity stages > Closed Won / Closed Lost. Key objects: Lead, Account, Contact, Opportunity, Quote, Product, Price Book, Forecast.
Service Cloud - post-sales customer support. Flow: Case creation (Web-to-Case, Email-to-Case, phone/CTI, community) > Assignment rules / Omni-Channel routing > Agent works the Case in the Service Console using Knowledge > Escalation rules and Entitlements/Milestones > Case closed. Key features: Case Management, Knowledge, Service Console, Live Agent/Chat, Omni-Channel, Field Service Lightning, CTI.
Marketing Cloud - campaign and journey management across email, SMS, social and advertising. Key tools: Email Studio, Journey Builder, Automation Studio, Mobile Studio, Audience Builder. (Account Engagement/Pardot serves B2B marketing automation.)
Commerce Cloud - B2C and B2B digital storefronts: catalogue, cart, checkout, order management and personalisation.
Community Cloud (now Experience Cloud) - connects and collaborates with customers, partners and employees. It provides a platform for building online communities and portals to enhance engagement and communication.
Experience Cloud - build digital experiences (sites, portals, help centres) for end users with no-code, low-code or pro-code. Built with Experience Builder templates and Lightning components; used for customer communities, partner communities and public sites.
Partner Community - an Experience Cloud site aimed at resellers/distributors (PRM). From Setup > Digital Experiences > All Sites you open the site in Experience Builder and change the layout, branding and pages per audience. Partner users get partner licences and see leads, opportunities (deal registration), and shared content.
Analytics Cloud (CRM Analytics / Einstein Analytics) - datasets, lenses, dashboards and predictive analytics over Salesforce and external data.
IoT Cloud - ingests device/sensor event streams and turns them into Salesforce actions via orchestration rules.
Heroku - a PaaS for building custom apps in open languages (Node, Java, Ruby, Python), integrated back into Salesforce with Heroku Connect.
Quip - collaborative documents, spreadsheets and chat embedded into Salesforce records.
Q857. Which platform is used for developing an app in Salesforce?
The Force.com platform (now called the Salesforce Platform / Lightning Platform) is used for developing apps in Salesforce.
Q858. How do you build a Salesforce mobile application?
The Salesforce Mobile SDK OR hybrid or React Native.
Q861. What is Salesforce Automotive Cloud?
Automotive Cloud provides features and tools built specifically for the automotive industry:
Customer 360 for automotive - a complete view of customer details and interactions across different touchpoints.
Digital retailing - easy online purchasing of vehicles, virtual showrooms and online buying and configuration experiences.
Service and maintenance management - managing customer service appointments and vehicle servicing smoothly.
Dealer Management System - managing inventory, sales and customers easily.
Connected car solutions - using vehicle telemetry to provide personalized services.
Partner Relationship Management - managing dealers, suppliers and partners in the ecosystem.
Analytics and reporting - dashboards and reports for the automotive business.
Artificial intelligence and machine learning - predictive analytics and personalized recommendations.
Q862. What is an App in Salesforce?
An app is a group of tabs that work as a unit to provide functionality. an "app" is a collection of objects.
Q864. What is the difference between Salesforce.com and Force.com?
Salesforce.com is a Customer Relationship Management (CRM) application built on a Software as a Service (SaaS) model - prepackaged solutions such as Sales Cloud and Service Cloud.
Force.com is the Platform as a Service (PaaS) underneath it, which helps developers and business users build their own powerful enterprise applications.
Salesforce.com is itself built on the Force.com platform.
Q865. What are tabs in Salesforce?
Tabs are the menu items of an app.
Q866. Who is a user in Salesforce?
A user is an individual who has credentials to log in to Salesforce and use the application. Each user has a unique username, an email address, a profile, an optional role, and a user licence that determines what they can access.
Q867. What is Chatter in Salesforce?
Chatter is a Salesforce real-time collaboration application that lets your users work together, talk to each other and share information - posts, comments, files, feeds, groups, following records and people, and @mentions.
Q868. What is a Community in Salesforce?
A Community cloud (now Experience Cloud site) is a way to allow your customers and partners to access your Salesforce org. With special community licences they get user accounts and a dedicated access portal, customized with Lightning features that can be configured without any code. It is also simple to layer in security so that they can only see or edit the objects and records you want them to.
Q870. What is case management in Salesforce?
Asked at: Accenture
Answer supplied - source left blank.
Case management is the Service Cloud functionality for capturing, routing, resolving and reporting on customer issues.
Capture channels: Web-to-Case, Email-to-Case (and On-Demand Email-to-Case), phone, communities, chat.
Routing: assignment rules, queues, Omni-Channel, escalation rules.
Automation: auto-response rules, case escalation rules, milestones and entitlements (SLAs), macros.
Resolution aids: Knowledge articles, Case Teams, Case Comments and Case Feed.
Statuses and record types drive the support process; reports and dashboards track volume, age and SLA compliance.
Also noted:
Case management in Salesforce refers to the process of tracking and resolving customer issues, questions, or service requests using the Salesforce platform - capturing cases from multiple channels, assigning and escalating them, and resolving them against SLAs.
Q871. What is the life cycle of Sales Cloud and which objects are used in it?
Asked at: Cognizant
The standard sales life cycle is:
Campaign > Lead (quick enquiry) > (on conversion) Contact & Account > Opportunity
Q872. Are you using the Lead object or the Opportunity object, and why do we use the Opportunity object instead of the Lead object?
Asked at: Cognizant
Both, at different stages.
The Lead is created first - it is an unqualified enquiry, and it holds the person and the company details in one record because they are not yet verified.
Once qualified, the Lead is converted into a Contact and an Account, and the actual deal (the enquiry with revenue, stage, amount and close date) is tracked on the Opportunity.
Q873. How does Salesforce compare with ServiceNow?
Salesforce ServiceNow
--- --- ---
Platforms Desktop, Mobile, Cloud Cloud
Type of software Standalone, Cloud, SaaS Standalone, Cloud, SaaS
Key features Marketing, Sales Management, Customer Management, Customer Service Information Technology, Customer Management, Customer Service
Price Preferred by all types of customers as it is cost effective Approximately four times more than Salesforce
Typical customers Small, Mid and Enterprise Mid and Enterprise
Security Moderate Best when compared to Salesforce
Q874. What is multitenant architecture?
An application model in which all users and apps share a single, common infrastructure and code base.
Q880. How does Salesforce deploy sales tracking?
Salesforce records data such as sales numbers, customer details, repeat customers and customers served, and uses these to create detailed reports, charts and dashboards. This is how it keeps track of sales in your organisation, with the Opportunity pipeline, forecasting and dashboards giving visibility at every level.
Q881. Can you see a converted lead in the Salesforce UI?
The lead detail record itself is not shown. Instead a page is displayed showing links to the resulting Account, Contact and Opportunity.
Q882. What is the full form of AJAX?
AJAX stands for Asynchronous JavaScript and XML.
Q883. Given a Salesforce record ID, how can you identify the object from the 18-digit ID?
The first 3 characters are the key prefix that signifies the object, and all records of that object always start with those 3 characters. For example, Account records start with 001.
Q884. What are the five standard fields that exist on every Salesforce object?
Every record carries a set of system/audit fields that Salesforce creates automatically:
Id - the record id, the default primary key (15 characters case-sensitive in the UI/URL, 18 characters case-insensitive in exports).
Name - the record name (text or auto-number).
CreatedById / CreatedDate.
LastModifiedById / LastModifiedDate.
OwnerId - the owner of the record (not present on detail objects of a master-detail relationship, which inherit the parent's owner).
Q885. What is Salesforce Einstein?
get the Answer from SSIA doc.
Einstein is Salesforce's layer of artificial intelligence built into the platform; it applies machine learning to the data already stored in the CRM so that predictions and recommendations appear inside the standard user interface.
Typical capabilities: Einstein Lead Scoring and Opportunity Scoring, Einstein Activity Capture, Einstein Forecasting, Einstein Case Classification and Bots in Service Cloud, Einstein Prediction Builder (point-and-click predictions on any object), Einstein Next Best Action, and Einstein Vision/Language APIs for image and text models in custom apps.
For developers, Einstein Prediction Builder and Next Best Action are declarative, while the Einstein Platform Services APIs let you train and consume custom image/text models from Apex or an external service.
Q886. Why do Salesforce record Ids come in 15-character and 18-character forms?
The 15-character Id is case sensitive, and is what you see in the Salesforce UI URL.
Classic view we can see 15 character and Lightning view we can see 18 character IDs.
Q887. How do you add a new user to your team in the Salesforce Partner Community?
Go to the Manage Users tab, choose to invite a user, and enter the person's email address. They receive an invitation and, once accepted, appear in your company's user list where you can grant or revoke their permissions.
Q888. What permission do consulting partners need in order to view their company's Consulting Partner Program Status and Certifications page?
The Manage Partners permission.
Q890. What community (Experience Cloud) licence types are available, and which account types do they support?
Experience Cloud uses community licences for access. There are five types:
1. External Apps - B2C
2. Customer Community - B2C
3. Customer Community Plus - B2C and B2B
4. Partner Community - B2B
5. Channel Accounts
There are two account types involved: Person Accounts (supported by Customer Community and Customer Community Plus) and Business Accounts (supported by Customer Community, Customer Community Plus and Partner Community), from which portal users are created.
HR / Behavioural
8 questions
Q891. Tell me about yourself.
Asked at: Accenture
Structure the answer as Present - Past - Future, kept to about 90 seconds and aimed at the role.
Present: Start with your current role, scope and the kind of work you own. Example: "I am a Salesforce Technical Lead/Architect with X years on the platform, currently leading a team of N developers across Sales Cloud, Service Cloud and Experience Cloud."
Past: Give two or three highlights that prove the claim - a large integration you designed, a migration you led, a performance or data-volume problem you solved - with the measurable outcome (time saved, users onboarded, defects reduced).
Future: Say why this role is the logical next step - "I am looking for a lead architect role where I own solution design end to end, which is exactly what this position is."
Tips:
Talk about your professional story, not your personal history.
Mention the technologies the job description names (LWC, Apex, integration patterns, DevOps tooling) so the interviewer can map you to the role.
Finish with a clear stop so the interviewer can ask the next question.
Also noted:
Keep it to about 90 seconds, stay factual and role-relevant, and finish by inviting the interviewer to dig into any project you mentioned.
Q892. What is your weakness?
Pick a real but non-critical weakness, then show the corrective action and the progress made. Never say "I have no weaknesses" and never pick something core to the job.
Framework:
Name the weakness honestly. Example: "I used to take on too much myself instead of delegating, because I knew I could deliver it faster."
Show the impact you noticed. "It became a bottleneck when I moved into a lead role and the team was waiting on my reviews."
Explain the fix. "I introduced a rotation for code reviews, wrote a design-review checklist, and started pairing juniors on the harder stories."
Show the result. "Review turnaround dropped from two days to a few hours and the team now handles most designs without me."
Other safe, genuine options: public speaking to large audiences, over-polishing documentation, impatience with slow decision-making - always paired with what you are doing about it.
Q893. What are your strengths?
Choose two or three strengths that match the job description and back each one with a short, concrete example (STAR style: Situation, Task, Action, Result).
Example set for a Salesforce lead/architect role:
Solution design under constraints - "I designed the integration layer for a Salesforce-to-SAP order flow using platform events and a middleware queue; it handled 200k orders a month within governor limits and cut sync failures to near zero."
Leading and mentoring - "I run design reviews and onboarding for new developers; three juniors on my team are now independently owning modules."
Bridging business and technical - "I gather requirements directly from stakeholders and translate them into a technical design the team can build without rework."
Tips:
Two or three well-evidenced strengths beat a long list of adjectives.
Use numbers wherever you have them.
Tie each strength back to what this employer needs.
Q894. Do you have any questions for us?
Always have questions ready - saying "no" reads as a lack of interest. Ask about the work, the team and the technology, not only about benefits.
Good questions to ask:
What does the delivery team look like, and where would I fit in it?
What are the biggest technical challenges the Salesforce org faces right now - data volume, technical debt, integrations?
What does the release process look like? Which DevOps tooling do you use (change sets, Copado, Azure DevOps, SFDX pipelines)?
How mature is the org - is it a greenfield implementation, or a long-lived org needing modernisation?
How is success measured for this role in the first 90 days and in the first year?
What are the opportunities for growth and certification support?
Close by restating your interest and asking about the next steps in the process.
Q895. What do you do on a daily basis?
Asked at: GenPact
Answer supplied - source answer was project-specific.
A good answer describes your routine concretely: attending the daily stand-up, picking up sprint user stories from the backlog, developing and unit-testing the assigned configuration/Apex/LWC work, handling defects and change requests (CDEX/bugs) raised against the current release, doing peer code reviews and commits to the version control branch, and coordinating with QA and the business analyst on acceptance. For example: "I am currently working on a Sales Cloud implementation, handling sprint user stories and resolving daily change requests and bugs."
Q896. Explain the most challenging module you have worked on.
Asked at: Cognizant
Answer supplied - source answer was incomplete.
Structure the answer with situation, task, action, result. A typical example: a large data migration from a legacy system into Salesforce, where the challenges were inconsistent source data, matching keys (solved with External ID fields and upserts), volume (solved with Bulk API and Batch Apex in scopes of 200), and downtime constraints (solved with a phased cut-over and reconciliation reports). Close with the measurable outcome - records migrated, error rate, and how issues were logged and resolved.
Also noted:
The challenges were mapping legacy fields to the Salesforce data model, de-duplicating and cleansing the source data, preserving record ownership and relationships (parent before child, External IDs as match keys), staying inside governor and API limits with millions of rows, disabling automation during load, and reconciling the counts afterwards.
Q897. Which cloud have you worked on?
Asked at: Cognizant
Sales Cloud - working with Leads, Accounts, Contacts, Opportunities, Products, Quotes, Campaigns, forecasting, reports and dashboards.
Q898. What are the skills required to become a Salesforce developer?
A Salesforce developer is someone with a solid knowledge of the Salesforce platform, and can move on to become a Salesforce administrator later in their career. The developer must understand how Salesforce works - the declarative platform (objects, fields, relationships, security, automation) plus the programmatic side: Apex, SOQL/SOSL, triggers, Visualforce, Aura and Lightning Web Components, integration/APIs, testing and deployment.
Some knowledge of basic OOP concepts such as class, object and attributes is required, along with an understanding of the layered approach across the user interface, business logic and data model.
Integration Architect — MCQ Bank
129 unique certification-style questions (110 repeats removed from the original 250). Correct answer shown after each question.
MCQ 1. Universal Containers has decided that they will be using the bulk API to migrate the existing data into Salesforce as they will be importing a total of 80 million records. While planning for the data migration, what techniques should the Architect recommend to make sure the load go according to schedule? Choose 2 answers
A. Pre-process data that the triggers and workflows can be deactivated.
B. Perform a test load using a full Sandbox prior to the Production load.
C. Perform loads over a weekend server resource availability.
D. Leverage several workstations, loading different objects simultaneousl
Answer: A, B
MCQ 2. Universal containers has a simple co -premise web app that is unauthenticated. What capability should an integration Architect recommend to make the app accessible from within Salesforce?
A. Apex callout
B. Visualforce
C. Custom Web tab
D. Lightning connect
Answer: C
MCQ 3. Which two statements are correct about External ID? Choose 2 answers
A. External IDs must be Text fields
B. External IDs are always searchable
C. External IDs fields are always unique
D. External IDs can be used to upsert records
Answer: B, D
MCQ 4. Universal Containers has just purchased large volume of contact data from an external vendor. The head of sales would like to use the new data set within the existing production org. The production org currently contains a large volume of contacts. What should an Architect recommend to prevent data duplication in salesforce?
A. Load the data into salesforce and then utilize the contact Duplicate Rule feature
B. Utilize an off-platform de-duplication tool prior to loading.
C. Create a de-duplication trigger before loading the data.
D. Utilize a batch apex process to de-duplicate the data after loadin
Answer: B
MCQ 5. Universal containers(UC) leverages the standard opportunity and opportunity product objects to manage their orders in Salesforce. When a deal is closed, all opportunity information, including products and billing contacts, must be send to their ERP application for order fulfillment. As UC has an "express shipping" guarantee, leadership would like order information sent to ERP as quickly as possible after the deal is closed? How should an Architect fulfill this requirement?
A. Write a nightly batch job to send customer information to ERP.
B. Write a visualforce page to send order information to ERP.
C. Write an opportunity trigger to send order information to ERP.
D. Write an outbound message to send order information to ER
Answer: C
MCQ 6. Universal Containers has built an integration using the SOAP API to load records from a back-office system into Salesforce. The records created in the back-office system must be loaded into Salesforce in almost real time, so a custommodule was written to identify CRUD events in the back-office system and perform sync with Salesforce. UC has several other systems that integrate with Salesforce through the SOAP API using separate integration users. What is a risk involved with this sort of integration?
A. Too many concurrent sessions
B. Reaching an API call limit.
C. Reaching a logins per Day limit.
D. Too many record-lock errors
Answer: B
MCQ 7. Universal Containers is building a managed package to distribute on the AppExchange. As part of the solution they would like to include authentication information (username/password) inside of the package for web service calls made from the package Universal containers web services. A Salesforce security review has flagged this as a security violation and the architect must decide how best to protect these credentials Which two methods should the architect consider in order to protect these credentials? Choose 2 answers
A. Utilize named credentials to store the username/password of the web service end post.
B. Utilize a custom object with an encrypted text field to store the username/password of the web service end point.
C. Utilize protected custom settings to store the username/password of the web service end point.
D. Store the username/password directly in the Apex class that will be obfuscated in the managed package.
Answer: A, C
MCQ 8. Which two automated methods should an architect use to solve an issue with duplicate contacts? Choose 2 answers
A. Write a Batch Apex class to manage the deduplication
B. Assign new contacts to queues to be reviewed by a data quality team.
C. Leverage an AppExchange data management toolto de-duplicate contacts.
D. Enable duplicate management in the org to prevent duplicate
Answer: C, D
MCQ 9. Which mechanism should an Integration Architect recommend to make a secure, authenticated connection to a remote system that results in the remote system trusting Salesforce?
A. Encrypt the Payload with a shared key.
B. Use a pre-shared key in a query parameter.
C. Implement two way (or mutual) SSL certificates.
D. Utilize CA - signed certificates on the hos
Answer: D
MCQ 10. Universal Container needs to integrate Salesforcewith several home-grown systems. These systems require custom code to be written in order to integrate with them, and the CIO argues that if custom code needs to be written, then there is no reason to invest in middleware Which three considerations should an Architect bring up to the CIO? Choose 3 answers
A. Performance
B. Error Handling
C. Bulkification
D. Orchestration
E. Logging
Answer: B, D, E
MCQ 11. As part of their customer setup process. Universal containers requires that any address put into Salesforce be validated by the US Postal Service. The customer must provide their address while they are on the phone with the Universal Containers representative. What two solutions should a Technical Architect recommend to fulfill this requirement? Choose 2 answers
A. Implement a VisualForce page that validates entered addresses against an API.
B. Write a trigger with an @future callout that validates addresses against an API.
C. Build a custom Address object and a trigger that will validate the address against the object.
D. Leverage an Appexchange application to validate addresses entere
Answer: A, D
MCQ 12. What are three capabilities of Salesforce Lightning Connect? Choose 3 answers.
A. Write to OData - Compliant data sources without APEX.
B. Read from OData - Compliant data sources without APEX.
C. Associate external object records to Salesforce Account records.
D. Write triggers and workflows on external objects.
E. Write SOQL queries on external object.
Answer: B, C, E
MCQ 13. Universal Containers would like to integrate Salesforce to their Accounting system. Salesforce must notify the accounting system for every new account that has been created. The security team will not allow Salesforce to integrate directly to the accounting system due to potential security issues. Which three stages should the Architect consider to reduce the security concerns for this Integration use case? Choose 3 answers
A. Terminate the SSL connection at a reverse proxy in the DMZ which establishes trust in the connection using mutual SSL.
B. Enable WS-security for the web services made between Salesforce and the accounting system.
C. Whitelist the Salesforce IP range on the firewall to ensure only Salesforce- originated traffic can penetrate the network.
D. Utilize an Enterprise Service Bus to ensure Accounting system credentials are not stores within Salesforce.
E. Enable platform encryption in the Salesforce org to ensure network communication to the Accounting system is encrypted.
Answer: B, D, E
MCQ 14. Universal Containers is hearing complaints from users that recently released changes arebreaking existing functionality. What type of testing program should a Technical Architect implement to reduce or eliminate this complaint?
A. Performance Testing
B. Unit Testing
C. Regression Testing
D. User Acceptance Testing
Answer: C
MCQ 15. Universal containers utilizes the REST API to update the multiple Salesforce objects in real time based upon changes from their ERP system. They recently started encountering API Limits and have consulted the Integration Architect on possible solutions. What two possible strategies should the architect consider? Choose 2 answers
A. Migrate the integration to the partner WSDL to support 200 DML operations in a single API call.
B. Migrate the integration to the Bulk API which does not count towards the API limits.
C. Utilize the REST API batch URI to consolidate 100 DML operations into single API call.
D. Utilize workflow outbound messaging which does not count towards the API limits.
Answer: B, C
MCQ 16. Universal Containers manages a catalog of over one million products that it makes available to its customers. The master product catalog is stored and managed in their ERP application with frequent updates made to the product catalog by their sourcing team. The sourcing team may update attributes such as price, general catalog availability, and the product description. When the sourcing team makes an update that change must go into effect during the next business day and there may be thousands of changes made over the course of the day. What integration pattern would you recommend to best manage this scenario?
A. Write a custom web service to accept product catalog changes from ERP.
B. Use the streaming API to receive product changes in real time from ERP.
C. Write an outbound message to send product changes in real time from ERP.
D. Build a scheduled ETL job to sync products on a nightly basis from ER
Answer: D
MCQ 17. Universal Containers has a customer setup process that relies on external database to send customers welcome & registration emails. When a customer contacts Universal containers via phone they need to receive the welcome email shortly following the conversation with the UC representative. Universal containers representatives work exclusively in Salesforce and any new customer contacts are created in Salesforce by the representative. The external database exposes a SOAP API for integration with other applications. What Salesforce technology best fulfills this requirement?
A. Write a nightly batch synchronization to send customer information to the external database.
B. Write an outbound message to send customer Information to an ESB.
C. Write an outbound message to send customer Information to the external database.
D. Write a trigger with an @future method to send customer Information to the external database
Answer: C
MCQ 18. Universal containers is hearing complaints from users that recently released changes while they meet the functional requirements are not actually usable and/or do not meet their expectations for user experience for example, a Visualforce page that takes too long to display the first page of data. Which two types of testing should a technical Architect implement to reduce or eliminate the complaint? Choose 2 answers
A. user Acceptance Testing
B. Unit Testing
C. Regression Testing
D. Performance testing
Answer: A, D
MCQ 19. Universal Containers has a customer setup process that relies on external database to send customers welcome & registration emails. When a customer contacts Universal containers via phone they need to receive the welcome email shortly following the conversation with the UC representative. Universal containers 100% Valid and Newest Version Integration-Architecture-Designer Questions & Answers shared by Certleader representatives work exclusively in Salesforce and any new customer contacts are created in Salesforce by the representative. The external database exposes a SOAP API for integration with other applications. What Salesforce technology best fulfills this requirement?
A. Write a nightly batch synchronization to send customer information to the external database.
B. Write an outbound message to send customer Information to an ESB.
C. Write an outbound message to send customer Information to the external database.
D. Write a trigger with an @future method to send customer Information to the external database
Answer: C
MCQ 20. Universal containers built an integration using the Bulk API to load records from a legacy system into Salesforce, Parallel option with batch size 1000 was used 100% Valid and Newest Version Integration-Architecture-Designer Questions & Answers shared by Certleader However, the batches often fail due to " Max CPU time exceeded"errors which could be resolved with a Similar batch size. What are two risks involved with batch sizes that are too small? Choose 2 answers
A. Possibilityof hitting the daily limit for number of batches.
B. possibility of very long bulk job execution times
C. Possibility of failures due to record-locking errors.
D. Possibility of hitting the "Too many concurrent batches" limi
Answer: B, C
MCQ 21. Universal Containers would like to integrate to an external system from Salesforce over a secure channel howeverthe external system does not support HTTPbasic authentication What approach should an integration Architect recommend that enables the external system to trust the data being received?
A. Digitally sign the Payload using a private key trusted by the external syste
B. B.Include a secret passphrase in the payload that is a validated by the external system.
C. Base64 encode the data to ensure untrusted 3rd parties don't see it.
D. Utilize a 3rd-party SSO solution to authenticate the sessio
Answer: C
MCQ 22. Universal containers built an integration using the Bulk API to load records from a legacy system into Salesforce, Parallel option with batch size 1000 was used However, the batches often fail due to " Max CPU time exceeded"errors which could be resolved with a Similar batch size. What are two risks involved with batch sizes that are too small? Choose 2 answers
A. Possibilityof hitting the daily limit for number of batches.
B. possibility of very long bulk job execution times
C. Possibility of failures due to record-locking errors.
D. Possibility of hitting the "Too many concurrent batches" limi
Answer: B, C
MCQ 23. Universal Containers is using the enterprise WSDL to integrate their financial system to salesforce, while reading y=the release notes for the upcoming salesforce release the architect discovers a new object will be added to the salesforce data model that would be beneficial for the financial system integration. What two actions should the architect take to ensure the new object will be available to the financial system integration? Choose 2 answers
A. Download the latest enterprise WSDL that contains the new object definition to generate Web service stubs for the new Salesforce object.
B. Download the latest partner WSDL that contains the new object definition to generate web services stubs for the new salesforce object
C. Migrate to the partner WSDL to generate a generic sObject service stub that can be leveraged for existing and future Salesforce objects
D. igrate to the metadata API to download the new salesforce sObject definition into the financial system integration.
Answer: A, D
MCQ 24. Universal containers would like to restrict access to Salesforce to only clients on their network Which two mechanisms should an Integration Architect utilize to prevent unauthorized clients? Choose 2 answers
A. Configure Login IP Ranges on any profiles used by Integration B.Use a login flow to validate the IP and request a 2nd factor if incorrect
B. Use a trigger to change the user's profile if their IP is not trusted.
C. Enable the "Lock sessions to the IP address from which they originated" settin
Answer: A, B
MCQ 25. Universal Containers is building an integration between Salesforce and their Accounting system. The integration will utilize outbound messaging with call back pattern to Salesforce. The security officer would like to understand the authentication solution. What are the three ways that the call back can authenticate itself to Salesforce? Choose 3 answers
A. Utilize the Enterprise WSDL login() operation to obtain a new session ID.
B. Utilize an oAuth Username-Password flow to obtain a new oAuth token for the session ID.
C. Utilize the REST API login() operation to obtain a new session ID
D. Utilize the session ID contained within the outbound message notification as the authorization header.
E. Utilize the partner WSDL with oAuth to obtain a valid oAuth token for the session I
Answer: A, C, D
MCQ 26. Universal containers has used Outbound Messaging to integrate with their billing system. Their billing system has frequent outages that don't last more than a couple of hours. Which two aspects of Outbound Messaging might the customer experience issues with as a result of these outages? Choose 2 answers
A. Out-of-order deliver
B. B.Duplicate messages
C. Orphaned Requests
D. Exceeding Governor Limit
Answer: B, D
MCQ 27. Universal containers has complex data transformation, error handling and process automation requirements as part of their integration strategy. What technology should an Architect recommend in order to minimize Salesforce code customizations?
A. Data Loader
B. Canvas
C. Process Builder
D. Middleware
Answer: D
MCQ 28. Which two approaches should an Integration Architect recommend to allow access to on-premise systems by Salesforce? Choose 2 answers
A. Place the systems in aDMZ.
B. Whitelist Salesforce IPs on the firewall.
C. Utilize two-way(mutual) SSL
D. Whitelist the corporate IPS in Salesforc
Answer: B, C
MCQ 29. Universal Containers would like to display data from an external system inside of Salesforce, and has chosen not to enable lightning Experience. They do not need the data for any other purposes within Salesforce. Which approach should an Integration Architect recommend that matches the Salesforce UI? Choose 2 answers
A. An iFrame embedding a custom .Net application that displays data from the other systems.
B. A custom visualforce page with a controller thats calls-out to the other systems.
C. A custom Visualforce page with client- side calls out to the other systems.
D. A middleware orchestration to continuously persist data from other systems into Salesforc
Answer: A, B
MCQ 30. What are two considerations to make when performing SOAP callouts from within Apex? Choose 2 answers
A. SOAP callouts consume API limits.
B. WSDL2Apex supports RPC-style SOAP callouts.
C. WSDL2Apex can be used to generate stub code.
D. SOAP callouts cannot occur after any DML statement
Answer: C, D
MCQ 31. What capability should an Integration Architect consider if there is a need to synchronize data changed in Salesforce to a 3rd party with a JSON-based API endpoint?
A. Use an outbound Message with the record's data.
B. Use lightning connect to save the data to an external object.
C. Use an Apex class to perform the REST callout asynchronously.
D. use the REST API with the content-Type headerset to "JSON."
Answer: C
MCQ 32. Universal Containers wishes to move data between 3 back office systems: ERP, financial and a legacy home-grown shipping system that will be replaced 3 months after integration is scheduled to be complete. What integration pattern should an architect recommend to ensure minimal throwaway code?
A. point-to-point
B. Web Mashup
C. MiddleWare
D. Apex batch Processing
Answer: C
MCQ 33. Universal Containers has decidedthat acquisition of other companies will be a key focus of their growth for the next several years. All acquired customer service agents will use UC's pre-existing customer support process built in Salesforce. the ERP application at any acquired company will not be immediately replaced, and customer service agents must be able to see up-to-date order status from all ERP systems. What recommendation should a technical Architect make to minimize complexity during new acquisitions?
A. Use custom Linksto direct users to the appropriate ERP system to view order status.
B. Build all Integrations as nightly ETL batches to minimize real-time overhead.
C. Leverage Apex callouts to integrate directly with acquired applications.
D. Use an ESB to abstract the Salesforce integration from other enterprise application
Answer: B
MCQ 34. Universal Containers would like to update their accounting system every time an opportunity is changed to Closed-Won their accounting system occasionally is offline for 3-4 hours to support month-end processing, and they would like the integration design to ensure that no transactions are lost during this down time. Which two integration designs should the architect consider? Choose 2 answers
A. Utilize the enterprise WSDL to query Salesforce from the Accounting system for opportunities that have changed to Closed-Won.
B. Utilize an Enterprise Service Bus to the web service calls between Salesforce and the accounting System.
C. Utilize workflow outbound messaging, which has a built-in queuing framework.
D. Utilize an Apex trigger with an @future class to callout to the accounting system after the monthend processing is complete.
Answer: B, C
MCQ 35. What are two scenarios that utilize the chatter REST API? Choose 2 answers
A. When integrating chatter into custom mobile apps.
B. When migrating Opportunity data.
C. When uploading large files.
D. When posting status updates to social medi
Answer: A, D
MCQ 36. What are the three capabilities of the Bulk API? Choose 3 answers
A. process multiple batch jobs asynchronously
B. Process multiple batch jobs synchronously
C. Roll back all transactions within a batch of 10000 records
D. Monitor job status via the API.
E. Monitor job status via the Web U
Answer: A, D, E
MCQ 37. When making an Apex callout, what approach should an Integration Architect recommend for securely transporting sensitive data from Salesforce over an unsecure network connection?
A. Base64 encode the data before performing the call out from Apex.
B. Encrypt the data with a shared key before performing the Apex callout.
C. Use platform Encryption to secure the data before transporting.
D. Salesforce automatically secures all data transmissions to external system
Answer: A
MCQ 38. Universal Containers has a requirement for users of a Validation page to be notified of data updates from Salesforce as well as message from other systems in real time. Which three approaches should be considered when selecting the correct API? Choose 3 answers
A. REST API to continuously poll Salesforce for updates to records.
B. Generic Streaming API to support notifications coming from other systems.
C. Streaming API to support push notifications to users on mobile devices using Salesforce1.
D. Utilize ActionPoller to perform an Apex Callout to the external system to retrieve data.
E. Streaming API to support real-time data updates by other users within Salesforc
Answer: C, D, E
MCQ 39. Universal containers is building an integration between their instance of Salesforce and their business partner's fulfillment systems, the security officer would like to ensure that only the authorized data for each business partner is accessible across all interfaces. How should the architect ensure this requirement is met?
A. provide each business partner a shared integration username/password with a specific role/profile provisioned to the appropriate data.
B. Provide each business partner their own username/password with a specific role/profile provisioned to the appropriate data.
C. Provide each business partner their own username/password with an Apex custom web service to filter the data appropriately.
D. Provide each business partner their own username/password with a shared integration profile provisioned to the appropriate data.
Answer: B
MCQ 40. Universal Containers has a requirement to query all Account records within Salesforce that were updated in the last 24 hours and download those Accounts to their data warehouse on a nightly basis. They expect the volume of records to be between 500-1500 records per day. What three techniques should an Architect consider ? Choose 3 answers 100% Valid and Newest Version Integration-Architecture-Designer Questions & Answers shared by Certleader
A. Leverage a time-based workflow action to trigger an account outbound message notification for all records updated within the last 24 hours.
B. Leverage the Enterprise WSDL getUpdated() operation to retrieve Account records updated within the last 24 hours.
C. Leverage the Salesforce Data Replication API getUpdated() operation to retrieve Accounts records updated within the last 24 hours.
D. Leverage a third party tool ETL with a dynamic changing SOQL to retrieve Accounts updated within the last 24 hours.
E. Leverage the REST API / sObjects / Account / updated URI to retrieve Accounts records updated within the last 24 hours.
Answer: B, C, D
MCQ 41. Universal Containers has a requirement to query all Account records within Salesforce that were updated in the last 24 hours and download those Accounts to their data warehouse on a nightly basis. They expect the volume of records to be between 500-1500 records per day. What three techniques should an Architect consider ? Choose 3 answers
A. Leverage a time-based workflow action to trigger an account outbound message notification for all records updated within the last 24 hours.
B. Leverage the Enterprise WSDL getUpdated() operation to retrieve Account records updated within the last 24 hours.
C. Leverage the Salesforce Data Replication API getUpdated() operation to retrieve Accounts records updated within the last 24 hours. 100% Valid and Newest Version Integration-Architecture-Designer Questions & Answers shared by Certleader
D. Leverage a third party tool ETL with a dynamic changing SOQL to retrieve Accounts updated within the last 24 hours.
E. Leverage the REST API / sObjects / Account / updated URI to retrieve Accounts records updated within the last 24 hours.
Answer: B, C, D
MCQ 42. Universal Containers wants to ensure Salesforce will only accept secure connections from their ETL tool. How should calls to a custom Apex web service be secured?
A. VPN
B. Two-way SSL
C. Profile Security
D. IP Whitelisting
Answer: B
MCQ 43. Universal containers ships millions of orders per year and releases code fixes to the production org mightily. Their corporate testing strategy requires that tests must be performed against Production data in an isolated test environment before code can be released to production. How can Universal Containers achieve the requirement?
A. Use Salesforce-to- Salesforce to keep data synchronized between production and full sandboxes.
B. Utilize a middleware solution and batch API to do a nightly synch from production to Full sandbox.
C. Create APEX unit tests so testing can be done against Production data, but rolled back before being committed.
D. Request that Salesforce to schedule a full sandbox refresh on a nightly basi
Answer: B
MCQ 44. What should an integration Architect consider when building a visulaforce page that makes clientside callouts to multiple domains that may violate the browser's same-origin policy? Choose 2 answers
A. Setup CORS to whitelist all domains that the client scripts communicate with.
B. utilize the canvas SDK to perform the callouts.
C. Ensure each javascript resource communicates only with its origin.
D. Set up Remote site settings for all domains that the client scripts communicate wit
Answer: A, D
MCQ 45. In order to avoid slowing down inbound call center sales agents, Universal Containers wants to deduplicate Lead records against their 3rd-party MDM system after that the agent has served the record in Salesforce. What integration strategy should an Architect recommend?
A. Outbound message to MDM with a callback to Salesforce to mark duplicate Leads.
B. Sync the MDM system to a custom object in Salesforce and execute a Lookup validation rule against the object.
C. Batch APEX process to de-duplicate all records first in Salesforce then against MDM, deleting the newest MDM record.
D. Use Out-of-the-Box Lead De-duplication Rules to checkagainst MD
Answer: A
MCQ 46. A system at Universal Containers needs to retrieve opportunity details(including line items and opportunity learn) and then update the opportunity with new information in real time, as one atomic operation. What approach should an architect recommend that conserves API limits?
A. Use a publisher action to update the data and callback to the other system.
B. Use the generic streaming API to publish changes and listen for updates.
C. Use the SOAP API to upsert the dat
D. The API will then return all opportunity details.
E. Use a custom Apex class with a webservice method that performs both actions.
Answer: D
MCQ 47. What are the two considerations of Apex REST services that an integration architect should keep in mind when building custom integrations? Choose 2 answers
A. They cannot utilize publisher actions.
B. They require unit and functional testing
C. They cannot be built or maintained declaratively
D. They consume more API limits than SOAP or REST API
Answer: A, C
MCQ 48. Universal Containers has chosen Salesforce Wave as their Analytics Platform. There is a requirement to join data from multiple systems(including Salesforce) to be displayed in a single Wave Lens. What should the Architect recommend?
A. Use an ETL tool to load the data into Salesforce, upserts to ensure that the data in properly joined.
B. Use Data flow to load Salesforce data, and an ETL tool to load other data sets.
C. Use an ETL tool to join multiple sources and load them into a single data set.
D. Use data flow to load Salesforce data,and lightning connect to access the other data sets in real time.
Answer: C
MCQ 49. Which tool would an architect likely leverage while diagnosing issues with an inbound RESTful integration to Salesforce?
A. Workbench
B. Data Loader
C. Force.com SOAP Explorer
D. Metadata audit trail
Answer: A
MCQ 50. Universal Containers is building a native mobile application that queries and updates data in their Salesforce in real time What statement is correct about the Salesforce APIs?
A. Enterprise WSDL minimizes payload size.
B. Rest API supports oAuth
C. Enterprise WSDL supports WS-Security
D. REST API supports WS-Securit
Answer: B
MCQ 51. Universal Containers decided to use Salesforce Sales Cloud for their sales processes. Won Opportuinities must be sent to an external source for Order fulfillment. All lint items must also be sent, along with opportunities. The ERP system has SOAP based web services orders. UC chose to use Apex callouts. Which two design trade-offs must be taken into account when using Apex callouts to SOAP base web services? Choose 2 answers
A. Too many callouts resulting in exceeding the daily limit for number of callouts.
B. Code changes may be required following upgrades to the ERP system.
C. DML operations are not allowed right after Apex callouts.
D. Appropriate error handling to retry failed message
Answer: A, C
MCQ 52. In which three ways can production data be moved into a sandbox for testing purpose?
A. Refresh a Full Sandbox.
B. Use the metadata API.
C. Request a Snapshot from Support
D. Refresh a Copy Sandbox.
E. use the Apex Data Loade
Answer: A, D, E
MCQ 53. An insurance company decides to build an online portal using the Salesforce platform for receiving quote requests from customers. The company has a legacy quoting system that will generate quotes while the rest of the sales process is managed by Salesforce Sales Cloud. The legacy system has an API for creating quotes. What Implementation method should be used so that customers can request quotes online and receive them in real time?
A. Middleware tool to pull quote requests from SF and push to the legacy system.
B. Trigger with an @Future method to send quote requests to the legacy syste
C. C.Outbound message to send quote requests from Salesforce to the legacy system.
D. Apex callout to send quote requests from Salesforce to the legacy Syste
Answer: D
MCQ 54. Universal Containers has an Outbound messaging-Based integration that posts closed opportunities to an ERP system for fulfillment in 1% of the test cases, the integration creates multiple orders for a closed opportunity Which three steps should a Technical Architect take to diagnose the issue? Choose 3 answers
A. Review the firewall logs to make sure that the outbound messages are being delivered.
B. Review the Enterprise Service Bus logs to make sure that successful orders are being acknowledged
C. Review at the outbound Messaging Deliverystatus logs to make sure that the messages are being delivered and acknowledged by the target system.
D. Review the Enterprise Service Bus logs t make sure that orders are being created only one time.
E. Review at the outbound Messaging Audit logs to make sure that the messages are being successfullyprocessed by the target system.
Answer: B, C, D
MCQ 55. What are two benefits of canvas that an Integration Architect should consider when exposing external systems from within Salesforce? Choose 2 Answers
A. Canvas can provide authorization information via the signed Request.
B. The canvas SDK can be used to make an external systems UI look like Salesforce.
C. Canvas can send data to an external system asynchronously.
D. Canvas endpoint URLs can be dynamically changed via a Lifecycle Handle
Answer: A, D
MCQ 56. Universal Containers wishes to validate street addresses in Salesforce against their legacy Accounting system,Which is the system of record. Retrieving an Account record in this system takes 7-12 seconds per query, and the address must be validated as quickly as possible to ensure proper order processing. What integration pattern should an Architect suggest?
A. Remote Invocation initiated by Middleware
B. @Future method with an Apex callout.
C. Nightly batch validating records modified the previous day.
D. Outbound Message with a Callbac
Answer: D
MCQ 57. try Universal Containers is planning a data migration into Salesforce and must decide whether to use the Bulk API or the SOAP API. Which three statements are true about the Bulk API and REST API? Choose 3 answers
A. DML limits on Bulk are not governed on Salesforce servers.
B. The SOAP API provides jpb monitoring on the Salesforce setup menu.
C. The Bulk API allows multiple attachments to be leaded from within a single ZIP file.
D. The SOAP API avoids record locking contention on parent objects of Master-Details relationship.
E. The Bulk API may cause record locking contension on parent objects od Master-Details relationship.
Answer: C, D, E
MCQ 58. Universal Containers has multiple Salesforce orgs as a result of a number of acquisitions over time. They decide to let the subsidiaries continue using their own orgs but would like to streamline their lead processing. They identified one org that would act as a gateway to receive all the leads for the group and then distribute them to subsidiary orgs based on lead type. Changes to lead status in subsidiary orgs must be refilected in the gateway org They decide to use Salesforce-to- Salesforce for lead distribution. What limitation of Salesforce-to-Salesforce must be considered to ensure searchless two-way integration?
A. Salesforce-to-Salesforce has no built-in support bi-directional(two-way) integrations.
B. Salesforce-to-Salesforce has a limit on number of records shared between systems.
C. salesforce-to-Salesforce does not support linking/sharing with existing records in a receiving org.
D. salesforce-to-Salesforce has no built-in support for objects with Parent-child relationship
Answer: D
MCQ 59. Universal Containers has two integrations to Salesforce; System A requires read-only access to all Opportunity data while System B requires read-write access to all Accounts. Which approach ensures compliance with the principal of least priviledge?
A. Utilize a single "Integration User" with the "Modify All data" profile setting enabled so that all integrations always have access to all data.
B. Utilize separate credentials and profiles for each integration, one having "view All" to ties and the other having "Modify All" to Accounts.
C. Use a single "Integration User" with profile settings restricted to "view All" for opportunity and "Modify All" for Accounts.
D. Utilize separate credentials for each system with both credentials having the "modify all data" permission on the profile.
Answer: C
MCQ 60. Universal containers is migrating to Salesforce from a legacy system with existing SMTP-based integrations. What Salesforce platform capability should an Integration Architect consider?
A. Custom Apex class with webservice methods that implement the SMTP protocol.
B. Custom InboundEmailHandler to process the messages.
C. Lightning connect with an oData/SMTP interchange.
D. Custom Apex batch job to check for SMTP message
Answer: A
MCQ 61. Universal containers merges with planetary shipping both companies use Salesforce for order processing and they decide to consolidate for processes. universal containers has well-established channels for receiving orders, so they decide to use Universal containers org for receiving and preprocessing of orders and Planetary Shipping's org for processing and fulfillment of orders. What is the best way to integrate the business processes of the companies?
A. Use Apex callout to push orders from universal Containers to Planetary Shipping
B. Use salesforce-to-Salesforce integration between Universal containers and Planetary shipping
C. Use Outbound messages to send orders from Universal Containers to Planetary shipping.
D. Use a Middleware tool to pull orders from Universal Containers and push to Planetary Shippin
Answer: B
MCQ 62. Universal Containers has a custom Salesforce UI that is used by all users to check on a container's status. This check is done via an integration to its back-end system which all users have access to. However, some users have a higher privilege access into that back-end system, which allows them to retrieve more details in the same container status check. Those users would like the same Salesforce UI to recognize their higher privilege access and display those extra details for them, but without allowing all users to see the same level of details. What is the recommended security approach to satisfy this requirement? 100% Valid and Newest Version Integration-Architecture-Designer Questions & Answers shared by Certleader
A. Named credential set with "per-user" identify type to control the Apex callout.
B. Custom permission to control the Apex callout to retrieve different levels of details.
C. Hierarchical custom setting to store back-end system user credentials and referenced in the Apex callout.
D. Permission set to identify users with higher-level privileges in order to control the Apex callou
Answer: A
MCQ 63. Universal Containers has Logistics Engineers that observe a near real-time dashboard in Salesforce of shipping containers that are in transit. Without leaving the dashboard, an Engineer can select a container to request an updated status on that container. These requests are handled by a proprietary shipping system that queues the requests to send to each container. Containers are connected devices and check in with the shipping system every 30 seconds to receive any status requests. What integration pattern or combination of patterns would be needed to connect Salesforce and the shipping system?
A. UI Update Based on Data Changes and Batch Data Synchronization
B. Remote Process Invocation-Fire and Forget, with UI Update Based on Data Changes
C. Remote Call-In, with UI Update Based on Data Changes
D. Remote Process Invocation-Request and Reply
Answer: B
MCQ 64. Universal Containers is building a mobile application that connects to Salesforce for reading and updating data What is the appropriate authentication solution?
A. Create a mobile Integration user ID whose credentials are stored within the mobile application code.
B. Prompt for the mobile user's username and Password; utilize the oAuth Username-Password flow to obtain an oAuth token. 100% Valid and Newest Version Integration-Architecture-Designer Questions & Answers shared by Certleader
C. Redirect to Salesforce via the User-agent oAuth flow to obtain an access token and refresh token.
D. Prompt for the mobile user's username and password; utilize the Enterprise WSDL login() operation to obtain a session ID.
Answer: C
MCQ 65. The Integration Team at Universal Containers is frustrated because the developers keep changing the data model and trigger behaviors during development, resulting in frequent rework and unexpected bugs lade in the development process. What two recommendations should a Technical Architect make to resolve this issue? Choose 2 answers
A. Implement a Regression Testing policy to catch issues earlier in the development process.
B. Use a requirements traceability matrix to track data model changes back to the requirement that prompted them.
C. Implement a continuous Integration process to identify issues earlier in the development process.
D. Encourage code developers and integration developers to work in separate sandboxe
Answer: B, C
MCQ 66. What is the recommended approach to implement a login authentication call for an inbound integration call to Salesforce?
A. Perform the login call only when the session/access token has expired or no longer works.
B. Perform the login authentication call before each integration call to Salesforce every time.
C. Only perform a single login call forever and store the session/access token permanently.
D. Perform the login authentication call before a single transaction of multiple calls to Salesforc
Answer: A
MCQ 67. Universal Containers has a SOAP-based integration that runs nightly to update the Product(Product2) object in Salesforce with updated product availability for over 500,000 products. The source system is a green-screen ERP that must be taken offline to produce nightly production reports, such as the inventory availability report used for this integration. The integration is performing very slowly and does not complete within the allocated four-hour time slot. What three recommendations might a Technical Architect make to resolve this issue? Choose 3 answers
A. Use outbound Messaging to notify Salesforce promptly when product availability changes in the source system.
B. Store the Salesforce Product ID in the source system to eliminate the need for External IDs and UPSERT API calls.
C. Pre-process the data to avoid the need for workflow rules or triggers
D. Use the Bulk API UPDATE or UPSERT records more efficiently.
E. Contact Salesforce support to request that they turn off record locking on the Product2 objec
Answer: B, C, D
MCQ 68. When an opportunity is closed in Salesforce, an order should be created in the back-office SAP system. At the end of the day, Universal Containers allows customers to call back and cancel an order within 24 hours. To cancel an order, the Sales Rep has to set the opportunity status to Open from Closed. The Sales Manager wants all opportunities that changed from Closed to Open to be sent over to the SAP system for order cancellation on nightly basis. Salesforce has a total of 20M opportunities. What is the recommended way to achieve this?
A. An ETL job to leverage Bulk API to extract modified opportunities.
B. An ETL job to leverage REST API to extract all opportunities.
C. An ETL job to leverage SOAP API to extract modified opportunities.
D. An ETL job to leverage SOAP API to extract all opportunitie
Answer: C
MCQ 69. Universal Containers is planning to develop a native mobile app for their employees to interact with Salesforce. Which two options should the Architect recommend?
A. Leverage Identity Product
B. Leverage SOAP API
C. Leverage Message Queue Product
D. Leverage REST API
E. Leverage Identity Product
Answer: D
MCQ 70. Universal containers uses a legacy system to receive and handle Level 1 service requests, and Salesforce service Cloud for Level2 requests and above, Cases will be pushed from the legacy system to Service Cloud by a nightly batch process. Once the cases are closed in SF, the case needs to be updated in the legacy system as soon as possible. How should the Technical Architect recommend that case status be updated in the legacy system?
A. Use Apex callout to send case status from Salesforce to the legacy system.
B. use Outbound messages to send status updates from Salesforce to the legacy system.
C. Use a middleware tool to pull case status from Salesforce and push to the legacy system at regular intervals.
D. Write an Apex web service returning case status, to be called from the legacy syste
Answer: B
MCQ 71. Universal Containers is planning to sue Bulk API instead of SOAP API to load 1 million activity records from Accounts. Opportunities, can Cases. Which are two advantages of using Bulk API over SOAP API?
A. Bulk API needs fewer network round trips to complete the data load.
B. Bulk API doesn't need a login to Salesforce and can process data offline.
C. Bulk API doesn't need XML processing and can send data using CSV.
D. Bulk API needs Partner WSDL, whereas SOAP API needs Enterprise WSD
Answer: A, C
MCQ 72. Which two options should be considered to permit automatic retry of failed updates when loading data into Salesforce? Choose 2 answers
A. Bulk API with serial option.
B. Standard API with parallel option.
C. Bulk API with parallel option.
D. Standard API with serial option.
Answer: A, C
MCQ 73. Universal Containers has 1,200 active users. Up until last year, they were creating a maximum of 200,000 orders a day. This year because of a new product launch, they are creating a maximum of 300,000 orders per day. They have a trigger on the Order object that has a @future method inside, which it calls via an external web service hosted on middleware. Due to this sudden growth, they have started seeing delays in web service calls where some of the calls are delayed for a few hours. What can be issue for this delay and what integration pattern would an Architect recommend?
A. The system is reaching daily limits of @future call
B. Replace the HTTP Callout with a Workflow Rule and Outbound messages.
C. The system is reaching daily limits of web service callout
D. Batch web service callouts to stay under the limit.
E. The system is reaching daily limits of @future call
F. Remove @future annotation and call the web service directly from the trigger. G. The system is reaching daily limits of web service callout H. Create a ticket to Salesforce support to increase the limit.
Answer: A
MCQ 74. Universal Containers (UC) has integrations developed between Salesforce and back-end ERP applications. During peak load, UC is getting an error at the integration layer indicating, "Login Rate Exceeded". Which two recommendations would mitigate this issue?
A. Use a different user for each integration.
B. Set the permission login to never expire for the user.
C. Cache the session ID to avoid a login call.
D. Keep re-typing the login call until it's successfu
Answer: A, C
MCQ 75. Universal containers has an ERP application where all customer orders are stored. There are millions of customer orders stored in the ERP application and a longtime customer may have thousands of individual orders. Additionally, some order informationmay house personally identifiable information that, due to company policy, can only be stored in ERP. Universal Containers would like the five most recent orders displayed on the account page in Salesforce How should an architect design this requirement considering both security and scalability?
A. Leverage the REST API to receive orders from the ERP system as they are created.
B. Leverage Salesforce Lightning Connect to display order information in Salesforce.
C. write an outbound message to receive orders from ERP system as they are created.
D. Build a scheduled ETL job to sync all customer order history in the orders objec
Answer: A
MCQ 76. Universal Containers has a custom Visualforce page that makes a callout to an external service to show historical sales data from the warehouse. Due to heavy usage and slow response time of the external web service, Salesforce continues to hit the Apex Concurrent limit. Assuming that external web service response time can't be improved, what changes can be made to the custom Visaualforce page and Apex Controller to avoid hitting the Apex Concurrent limit?
A. Use @future annotation to make the HTTP Callout.
B. Replace the standard HTTP Callout with Continuation.
C. Invoke a Workflow Outbound message from the Apex trigger.
D. Set a timeout on the web service HTTP callou
Answer: B
MCQ 77. Universal Containers (UC) has an ERP application where all customer orders are stored. There are millions of customers order stored in the ERP application and a longtime customer may have thousands of individual orders. Additionally, some order information may house personally identifiable information that, due to company policy, can only be stored in ERP. UC would like the five most recent orders displayed on the account page in Salesforce. How should an Architect design this requirement considering both security and scalability?
A. Leverage Salesforce Connect to display order information in Salesforce.
B. Write an outbound message to receive orders from ERP system as they are created.
C. Build a scheduled ETL job to sync all customer order history in the Orders object.
D. Leverage the REST API to receive orders from the ERP system as they are create
Answer: A
MCQ 78. Universal Containers has a batch integration that runs every five minutes to load Shipment records related to existing orders that have been updated in the previous five minutes. the integration is not reporting any errors, but some Shipment records are not being loaded. What could be the problem?
A. Error reporting is not enabled in Salesforce.
B. The integration takes more than five minutes to run.
C. The integration is causing UC to exceedits API limits
D. The Integration cannot find the parent orders for some Shipment
Answer: B
MCQ 79. Universal Containers has a homegrown application that polls Salesforce using SOAP API every 2 minutes to obtain newly created case information. This causes both performance issues and API usage limits to be exceeded. What should an Architect recommend to improve performance and optimum use the API limits?
A. Use an Apex callout to identify new case records and send them to the client.
B. Use Streaming API to publish new case records to a push topic and subscribe to it.
C. Use Generic Streaming to send push notifications of case creation events to the client.
D. Use REST API to identify new case records in Salesforce every 15 minute
Answer: B
MCQ 80. Universal Containers (UC) uses several systems as part of their enterprise system landscape, including Salesforce and an ERP system. Salesforce is the master system for CRM data, such as Accounts and Opportunities. The ERP system is the master system for customer orders, shipping, and billing information. As part of 100% Valid and Newest Version Integration-Architecture-Designer Questions & Answers shared by Certleader their business process flow, when an order is created in the ERP system, it also needs to be created in Salesforce in real time. Which two options should UC consider to ensure duplicate Orders are not created in Salesforce?
A. Use outbound messaging to send a unique message ID to the ERP system.
B. Use the upsert() function instead of create() to prevent the creation of unwanted duplicate records.
C. Use a middleware tool to handle the responsibility for managing multiple duplicate calls.
D. Customize the Apex web service REST call to send a unique message ID to the ERP syste
Answer: B, C
MCQ 81. Developers at Universal Containers have created a custom command-line tool to help with their application lifecycle management by allowing them to deploy metadata changes such as page layouts, custom labels, and list views to their org using the Metadata API. What integration pattern does this tool utilize?
A. Request and Reply
B. Fire and Forget
C. Remote Call-In
D. UI Update Based on Data Changes
Answer: A
MCQ 82. Universal Containers (UC) wants to connect their on-premise ERP system to view Order data in Salesforce. UC is considering a solution to integrate the onpremise system using Salesforce Connect via OData. Which three considerations should an Architect keep in mind when recommending use of Salesforce Connect?
A. Customer wants the ability to query external data using Global Search and reports.
B. Customer does not want real-time access to the ERP data and is willing to wait for hourly refreshes.
C. Customer wants to create a master-detail relationship between Opportunity and the external object.
D. Customer needs to query small amounts of data at any time and display using a related list.
E. Customer has a large amount of data that they do not want to load into Salesforc
Answer: A, D, E
MCQ 83. Universal containers is building an integration from their employee portal to salesforce Chatter.They would like their employee portal to read and write to the Chatter API on behalf of the employee using the portal. What is the correct way to authenticate to the chatter API to meet this requirement?
A. Use oAuth to authorize the portal to access the chatter API on behalf of the user.
B. Use oAuth Which will pass their portal credentials to the chatter API.
C. Use a chatter API integration user which authenticates to salesforce using oAuth.
D. Use a chatter API integration user which authenticatesto Salesforce using Enterprise WSDL login().
Answer: C
MCQ 84. Universal Containers is integrating their Salesforce platform with their on-premise ERP system. As part of the test class design DML operations are to be performed before making the test callout. What capability does Salesforce provides to facilitate this?
A. Perform the DML operation within the Test.StartTest and Test.Stop Test and make the callout within Test.StartTest and Test.StopTest block.
B. Perform the DML operation outside the Test.StartTest and Test.StopTest and make the callout with the Test.StartTest and Test.StopTest block.
C. Perform the DML operation inside the Test.StartTest and Test.Stop Test and make the callout outside the Test.StartTest and Test.Stop Test block.
D. Perform the DML operation outside the Test.StartTest and Test.StopTest and make the callout outside of the Test.StartTest and Test.StopTest block.
Answer: B
MCQ 85. UC leverages external MDM as the customer master. When an agent creates or updates an account in Salesforce, it must be created/updated in MDM before it is saved in Salesforce. Sales users should be allowed to navigate to other pages while the account record is saved. What is the recommended approach?
A. Make an @future callout to MDM from a trigger with page refresh using Action region.
B. Make a continuation callout from VF page controller with page refresh using Action poller.
C. Make an asynchronous callout from VF page controller with page refresh using Action region.
D. Make a synchronous callout from VF page controller with page refresh using Action regio
Answer: B
MCQ 86. Universal Containers (UC) maintains the Customer Master outside of Salesforce and would like to sync the Customer records with Salesforce on a daily basis. UC has complex logic in the Account trigger and will have to test it for bulk inserts and updates. UC has been given a csv file with test data. What is the recommended way to use this data in a test class?
A. Load the customer-provided csv file as a static resource and refer to it in the test classes.
B. Load the customer-provided csv file as a Chatter file and refer to it in the test classes.
C. Load the customer-provided csv file under Documents and refer to it in the test classes.
D. Load the customer-provided csv file to a custom object for testing and delete the test records after testing.
Answer: A
MCQ 87. Universal Containers (UC) maintains the Customer Master outside of Salesforce and would like to sync the Customer records with Salesforce on a daily basis. UC has complex logic in the Account trigger and will have to test it for bulk inserts and updates. UC has been given a csv file with test data. What is the recommended way to use this data in a test class? 100% Valid and Newest Version Integration-Architecture-Designer Questions & Answers shared by Certleader
A. Load the customer-provided csv file as a static resource and refer to it in the test classes.
B. Load the customer-provided csv file as a Chatter file and refer to it in the test classes.
C. Load the customer-provided csv file under Documents and refer to it in the test classes.
D. Load the customer-provided csv file to a custom object for testing and delete the test records after testing.
Answer: A
MCQ 88. Universal Containers would like to use a hard-coded username/password/security token of a user with a System Administrator profile to integrate its back-end system to Salesforce for inbound API calls. Which two security issues are associated with this approach.
A. All back-end systems get uncontrolled access to any data within the Salesforce environment.
B. Unintended password resets will cause the integration to stop working and disrupt business processes.
C. Apex web services can executive with system privileges with such Salesforce credentials.
D. Unsecure storage of the credentials may result in hackers gaining unauthorized access to Salesforce.
Answer: A, D
MCQ 89. What are three capabilities of Salesforce outbound messaging? Choose 3 answers
A. Provide a session ID as part of the outbound message.
B. Repeatedly send a SOAP notification for up to 24 hours until an acknowledgement is received.
C. Build integration components without the Use of APEX.
D. Define a WSDL based upon 2 objects related via Master-Detaikls relationship.
E. Define a custom WSDL based upon an Apex Interface class definitio
Answer: A, B, C
MCQ 90. Universal Containers (UC) is planning on a production release with a large data volume to be migrated to Salesforce from a back-office system. The incoming data is constantly being updated in the back-office system. UC would like to keep the data synchronized in near real-time in Salesforce. What is the recommended approach to achieve this?
A. Use Bulk API for a one-time migration and an Apex web service call-in for an incremental load.
B. Use Bulk API for a one-time migration and a SOAP API call-in for an incremental load.
C. Use SOAP API for a one-time migration and a REST API call-in for an incremental load.
D. Use Bulk API for a one-time migration and a Bulk API call-in for an incremental loa
Answer: A
MCQ 91. Universal Containers (UC) has third-party MDM database which is responsible for maintaining the data for Customer and Contacts information for its organization. UC wants to keep this information up-to-date in Salesforce so that the information is as current as possible. UC wants to provide bidirectional synchronization of the data between the MDM and Salesforce. What is the recommended approach to solving this problem?
A. Create a VisualForce page for Accounts/Contacts that will pull the data from MDM, display it, andsend any changes from Salesforce.
B. Implement a third-party middleware tool to maintain the synchronization between Salesforce and the MDM database as they occur.
C. Create a Batch process that runs every 5 minutes to pull the changes from MDM and any updates from Salesforce.
D. Modify the MDM database application to send and receive updates to and from Salesforce via REST or SOAP as they occur.
Answer: B
MCQ 92. Universal Containers has a trigger on the Order object to update the parent Acount with the date and time of the last closed Opportunity. An integration that inserts orders for the high-volume customers is failing periodically, with no obvious pattern to the timing of failures. What could be the cause of this issue ?
A. The trigger is failing Unit Tests that access the new data.
B. API limits being limited.
C. Data skew is causing record locking issues on the Oder Share object.
D. Record locking contention on the parent Accoun
Answer: D
MCQ 93. When a Sales Rep closes an opportunity in Salesforce, an Order should be created in Universal Containers' SAP system and the Sales Rep should be notified with an order number as soon as possible. What is the recommended solution?
A. Apex @ future callout from an update trigger with an opportunity page refresh using Streaming API.
B. Workflow Outbound message with an email notification on callback from SAP
C. Apex callout from an update trigger with an opportunity page refresh using Streaming API.
D. Workflow Outbound message with an email notification on acknowledgement from SAP
Answer: B
MCQ 94. What are two reasons an existing custom field cannot be marked as External ID? Choose 2 answers
A. Maximum number of External IDs allowed on an object has been reached,
B. Maximum number of fields of an object has been reached.
C. Maximum number of skinny tables has been reached.
D. Maximum number of indexes allowed on an object has been reache
Answer: A, D
MCQ 95. Universal Containers needs to send order details to the ERP system using an Apex callout to a REST API via HTTPS. The client has concerns with the integration's security and insists that such order details should be transmitted securely. Which two approaches should be used to ensure secure transmission of data from Salesforce to the ERP's REST API?
A. The REST API should be SSLO enabled with a CA-signed certificate.
B. The order details should be passed in a URL parameter in the REST API endpoint.
C. The REST API should be SSL enabled with a Salesforce client certificate.
D. The order details should be passed in the body of the REST API callou
Answer: A, D
MCQ 96. Universal containers is implementing Salesforce for the first time. As part of the implementation, approximately 10 Million contact records need to be migrated into the new environment. What tool should an architect recommend?
A. Salesforce Data Loader
B. Data Import Wizard
C. Excel connector
D. Salesforce Workbench
Answer: A
MCQ 97. Universal Containers has a requirement to update the Salesforce Account object any time the corresponding account is updated within their financial system. Which three Salesforce capabilities should the Architect consider?
A. Partner WSDL because of a requirement to utilize SOAP-based web services.
B. Partner WSDL because of a requirement to dynamically inspect field names during runtime.
C. Streaming API because of a requirement to dynamically inspect field names during runtime.
D. Enterprise WSDL because of a requirement to utilize SOAP-based services
E. Partner WSDL because of a requirement to utilize REST-based web services
Answer: A, B, D
MCQ 98. Universal Containers (UC) has many existing applications, including Salesforce, that their users access. UC would like to integrate these applications with Salesforce so that users can accomplish all of their tasks in one user interface. What is the recommended solution for integrating these applications into Salesforce?
A. Set up the external applications as Connected apps into the Salesforce user interface.
B. Use streaming API to integrate these applications into the Salesforce user interface.
C. Set up the external applications as Canvas apps into the Salesforce user interface.
D. Connect the external applications into the Salesforce user interface using Salesforce Connec
Answer: C
MCQ 99. Universal Containers is currently doing User Acceptance Testing for small changes in a Developer sandbox. Users are complaining that allow release to production, some functionality is broken and performance is often negatively impacted. What is causing these complaints?
A. Users should be testing in a Partial Sandbox in order to replicate Production functionality and performance characteristics.
B. Users should be testing in a Full Sandbox in order to replicate Production functionality and performance characteristics.
C. Users should be testing with date loaded into the Developer sandbox in order to replication Production functionality and performance, characteristics.
D. Users should be testing in a Developer Pro sandbox in order to replicate Production functionality and performance characteristics.
Answer: B
MCQ 100. What Salesforce technology should an Integration Architect consider when needing to securely expose an external system User Interface from within the Salesforce UI and provide that system with information about the user?
A. Visualforce
B. Custom Web Tab
C. Canvas
D. Lightning Component
Answer: C
MCQ 101. Universal Containers (UC) uses several systems as part of their enterprise system landscape, including Salesforce and an ERP system. Salesforce is the master system for CRM data, such as Accounts and Opportunities. The ERP system is the master system for customer orders, shipping, and billing information. As part of their business process flow, when an order is created in the ERP system, it also needs to be created in Salesforce in real time. Which two options should UC consider to ensure duplicate Orders are not created in Salesforce?
A. Use outbound messaging to send a unique message ID to the ERP system.
B. Use the upsert() function instead of create() to prevent the creation of unwanted duplicate records.
C. Use a middleware tool to handle the responsibility for managing multiple duplicate calls.
D. Customize the Apex web service REST call to send a unique message ID to the ERP syste 100% Valid and Newest Version Integration-Architecture-Designer Questions & Answers shared by Certleader
Answer: B, C
MCQ 102. Universal containers has built an integration module to pull customer support tickets out of various systems and push them to salesforce as cases. The integration was implemented using Salesforce SOAP API with batch size 200, and the jobs are scheduled to run every 30 minutes to make sure a job completes before the next job starts. After going Live, they found that jobs are failing occasionally due to a "Max CPU time exceeded" error thrown from a trigger on the case. Reducing the batch size to 100 would resolve the issue, but the jobs would then take an average of 35 minutes to run. Which two options should be considered to resolve the issue and make sure a job completes before the next one starts? Choose 2 answers
A. No change to API options, and move the trigger code into a future method.
B. No change to API options, and move the trigger code into a Queuetable apex
C. Bulk API with serial option and batch size 100, and no code changes
D. Bulk API with parallel option and batch size 100, and no code change
Answer: A, D
MCQ 103. What are two benefits of named credentials? Choose 2 answers
A. They simplify utilizing oAuth for Apex callouts.
B. They Secure integrations to Salesforce from other systems.
C. They enforce secure communication to external systems
D. They securely store credentials in a maintainable wa
Answer: A, D
MCQ 104. Universal Containers (UC) has multiple orgs with Sales and Service Cloud implementation to support different lines of business. UC is planning to consolidate Salesforce orgs to benefit from a 360-degree view of the customer based on revenue, support requests, and contracts. What should an Architect recommend?
A. Use staging tables with an ETL tool for data cleaning and standardization.
B. Use a custom REST service for data cleaning and standardization.
C. Use a custom SOAP service for data cleaning and standardization.
D. Use standard SOAP API for data cleaning and standardizatio
Answer: A
MCQ 105. Universal Containers leverages Sales Cloud as their sales platform. For every opportunity, three backoffice systems need to be updated online in parallel under a single transaction, Unit of Work. If an update to one of the systems fails, a rollback is required for all successful updates in the transaction. Each system exposes different Services for the update and Call to the Services may take more than 10 seconds. Which two options should an Integration Architect introduce to support this requirement?
A. Salesforce Outbound Messaging
B. Integration Middleware
C. Message-oriented Middleware
D. Salesforce Continuatio
Answer: A, C
MCQ 106. Universal Containers (UC) sends Order data to an external ERP system via ESB. UC sends an outbound message on update or Order to ESB. Once ESB completes creating the Order in the backend ERP, it send back the Order with the Order Number from the ERP. During development, UC is experiencing an issue. When the Order is updated by ESB, it again fires a workflow rule that sends the outbound message again. Which two recommended steps can be done to prevent this looping issue?
A. Write an Apex trigger to send an outbound message to ESB.
B. Update workflow rule conditions to exclude the ERP Order Number field update.
C. Update workflow rule conditions to exclude the Integration User.
D. Update the outbound message to exclude the Integration User.
E. Update workflow rule conditions to exclude the ERP Order Number field updat
Answer: C
MCQ 107. Universal Containers acquiresplanetary shipping and decides to migrate all customer contacts of planetary Shipping into Universal Containers Salesforce org Due to the lack of common unique identifier, they decide that a combination of first name, last name and street address could be used as a key to identify duplicate contacts. These three fields are populated on all contacts in both the systems. Which two methods should be considered to load contacts into Universal Containers org and avoid creation of duplicate contacts? Choose 2 answers
A. Create a new text field to contain a hashed value for (first name+last name + street number) in Universal containers org and define it as External ID.
B. Create an indexed formula field for (first name+last name + street number) so that a search can be done on the key before loading records.
C. Create a new formula field for (first name+last name + street number) in universal containers org and use it as External ID.
D. Create no new fields, but define the three fields (first name+last name + street number) as External IDs in universal Containers org.
Answer: A, B
MCQ 108. Universal Containers (UC) has Wave Analytics in their Salesforce org. UC has expertise and access to the Dell boomi ETL tool. UC would like to get all leads and opportunities from the org and data from a few other Marketing tools to a Wave instance for enhanced analysis. What is the recommended solution to set up the data process?
A. Dell boomi for data from Salesforce and data from other sources.
B. Wave Data flow for Salesforce data and Dell boomi for data from other sources.
C. Export data from all sources into Excel and use Wave connector to import data.
D. Use Wave data flow for Salesforce data and data from other source
Answer: B
MCQ 109. Universal Containers requires Salesforce to send order data to an ERP system that requires a systemdefined username/password for authentication. Which two integration options are recommended from a security perspective?
A. Fire outbound messages to a middleware that stores the credentials instead of an Apex callout.
B. Use custom settings to store the username and password allowing the Apex callout to read it.
C. Set up a Named Credential with a Named Principal Identity Type allowing the Apex callout to use it.
D. Store the username/hashed password in a private Static Resource, allowing the Apex callout to read it.
E. Use custom settings to store the username and password allowing the Apex callout to read i
Answer: C
MCQ 110. UC leverages customer MDM as a source of truth. The requirement is to dedupe and store any account or contact created in MDM before the same is created in Salesforce. This ensures data is clean and not duplicated in Salesforce. During peak season, users experience a "Concurrent Request Limit Exceeded" error. What is the recommended solution?
A. Invoke a continuation callout to MDM from a VF Page controller.
B. Invoke a continuation callout to MDM from a before insert trigger.
C. Invoke a continuation callout to MDM from a VF Page JavaScript.
D. Invoke a continuation callout to MDM from a VF Page @future cal
Answer: A
MCQ 111. Universal Containers is replacing a home-grown CRM system. Currently, a .Net application runs a batch process to query the CRM system nightly and create a CSV file that is picked up via SFTP and loaded to a SQL database. What technology should an architect use to minimize custom development when replacing the CRM system with Salesforce?
A. Outbound messaging
B. APEX Batch
C. APEX Callout
D. Middleware
Answer: D
MCQ 112. Universal Containers (UC) stores inventory of products in one Salesforce org. UC wants regional and local branch offices who have their own Salesforce orgs to see the latest information about the product. What is the recommended approach to provide data access?
A. Use Heroku Connect to provide access to products as external objects from other orgs.
B. Use Salesforce Connect with oData to provide access to products as external objects.
C. Use Apex HTTP Callouts to call Salesforce Rest APIs and provide access restrictions within the Apex class.
D. Use Cross-Org adapter for Salesforce Connect to provide access to products as external object
Answer: D
MCQ 113. Universal Containers has an external ERP that will manage inventory and initiate shipping logistics after an Opportunity is marked "Closed Won" in Salesforce. A "Shipping Number" needs to be written back to the Opportunity to track related records in the ERP. Sales Reps need to move quickly from one Opportunity to the next. What integration pattern will satisfy the system reqs while maximizing the efficiency of the Sales Reps?
A. Remote Process Invocation - Fire and Forget
B. Batch Data Synchronization
C. Remote Process Invocation - Request and Reply
D. Remote Call-In
Answer: A
MCQ 114. Universal Containers (UC) would like to provide near real-time updates on their customer-facing external portal when a Sales Manager approves a new feature that is recommended by a customer. UC has no middleware, and the portal exposes a REST API therefore, UC is considering a custom-built system process to handle the integration. What is the recommended approach for the custom-built system process to retrieve updates in near real-time?
A. Leverage a related push topic that pushed information to the portal client.
B. Leverage a Streaming API client to subscribe to the related push topic.
C. Leverage Canvas to send information to the portal whenever an idea is voted on.
D. Leverage an outbound message to the portal whenever an idea is voted on the saved.
Answer: B
MCQ 115. Universal Containers (UC) is planning to roll out a new Force.com app to a regional business unit. UC has partial copy and a full sandbox available for deployment. UC's Architect has been asked to design an environment strategy for integration testing and performance testing, as well as user acceptance testing. What is the recommended use of available sandbox types that an Architect should consider?
A. Use the partial copy for performance testing and full sandbox for integration and user acceptance testing.
B. Use the full sandbox for performance and user acceptance testing and the partial copy for integration testing.
C. Use the full sandbox for integration testing and the partial copy for user acceptance and performance testing.
D. Use the full sandbox for user acceptance testing and use the partial copy for integration and performance testing.
Answer: B
MCQ 116. Universal Containers send quotes to customers periodically when the customer contract is near expiration. Quoting is generated by an external quoting engine. The VP recommends that the quotegenerated request should be sent one week prior to the contract expiration. The Quote engine requires the latest account, contact, and contract information from Salesforce to generate the quote. What is the recommended solution?
A. A scheduled batch Apex to gather additional information from Salesforce and make a sync callout to the quote engine.
B. Workflow-initiated alert to the Sales Rep, who will submit a request from a custom controller in a Visualforce page.
C. Workflow-initiated outbound message with a callback to gather additional information from Salesforce.
D. Workflow-initiated Apex to gather additional information from Salesforce and make a sync callout to the quote engine.
Answer: A
MCQ 117. Universal Containers would like to send all the closed opportunity records to the back-end legacy order management system. The order management system exposes REST API endpoints. What is the recommended approach to send the data to the order management system?
A. Workflow Outbound SOAP API message to a middleware system.
B. Workflow Outbound SOAP message to the order management system.
C. Workflow Outbound SOAP message to a middleware system.
D. Workflow Outbound REST message to the order management syste
Answer: C
MCQ 118. Universal Containers is using Sales Could with Order Capture. It has been integrated with an SAP system for Order fulfillment. The SAP system sends the Order status updates to Salesforce on a nightly basis. The SAP system tracks Order status more granularly than required by Salesforce. Which two options should an Architect recommend to address different statuses in Salesforce and SAP?
A. Create a batch Apex to run on a daily basis, which converts order status to pre-defined order status.
B. ETL Change Data Capture interface to send only required status updates to Salesforce.
C. ETL change Data capture interface transforms the SAP order statuses to Salesforce order status.
D. Update the SAP Order fulfillment process to match Salesforce Order Statuses against the SAP order status.
Answer: B, C
MCQ 119. Universal Containers (UC) has an existing web-based application that a group of employees use on a regular basis. These employees often have Salesforce and the web-based application open and find themselves manually moving the data between both. UC would like the two systems to be integrated so that the employees will see all the data in one screen without the need for manually updating the data. What integration pattern can help accomplish this requirement?
A. Use the Force.com canvas framework to embed the external application into Salesforce.
B. Use Steaming API to create a push topic to send the message to the external system asynchronously.
C. Use Rest API to pull data from Salesforce and update the external applicatio
Answer: A
MCQ 120. Universal Containers (UC) wants to start sharing some of the information collected from customers in Salesforce to other systems. UC wants to start sharing some sales data (orders) with a third-party application to help forecast inventory. This is a web application that supports SOAP and REST interfaces to send and receive data. What is the recommended solution for integrating with this product?
A. Create a Submit to Forecast Button on the Order Page to send the data to the Web application via REST.
B. Configure an Outbound Message to send a SOAP call via a Workflow rule to the Forecasting application on close.
C. Create an APEX trigger that makes the REST callout to the Forecasting application with the data when the deal closes.
D. Utilize a third-party ETL tool to synchronize the data from Salesforce to the Forecasting application using the Bulk API.
Answer: A
MCQ 121. Universal Containers has a back-end ordering system that restricts access on a per-user basis, it was determined that a "Named Credential" will be used to allow per-user identity type access for all integration with the system. One of the requirements is to have order information sent to the system when the status changes to "Confirmed". Which two valid integration scenarios can take advantage of such a security setup?
A. Order information sent to the system via outbound message with session ID.
B. Order information sent via a Visualforce page with an Apex callout.
C. Order information inserted or updated via Salesforce Connect: OData 2.0.
D. Order information sent via process builder via invokable method/future method callou
Answer: C, D
MCQ 122. Universal Containers (UC) has Salesforce integrated with their mainframe system. All the orders placed in Salesforce are sent to the mainframe system in a nightly batch process. Which two capabilities are required for middleware to support this integration?
A. Support for Metadata API
B. Extract, transform, and load
C. Message queuing
D. Synchronous transactions
Answer: B, C
MCQ 123. Universal Containers' Customer Service Managers wants to be automatically notified when a Customer Service Representative successfully closes a case What is the recommended approach for the Service Manager to be notified in the Salesforce user interface without having to refresh the screen?
A. Have the user refresh the standard Visaulforce page to see closed case updates by setting up the refresh interval on the browser.
B. Use a standard Visualforce page and embed JavaScript in the standard Visualforce page to refresh the porting of the standard page layout.
C. Create a custom Visaulforce page, subscribe to the "closed cases" push topic, and display alerts onscreen.
D. Create a custom Visualforce page with a custom polling mechanism to poll for closed cases and display alerts on the Visualforce page.
Answer: C
MCQ 124. Customer Support Reps at Universal Containers (UC) work on a Case record in Salesforce while talking to a customer on the phone about a piece of machinery they have purchased from UC. This machine is a connected device and sends data packets to UC as the customer presses buttions on the machine. What integration pattern will allow the support Rep to watch their screen and diagnose problems customer is having in near real-time?
A. UI Update Based on Data Changes
B. Remote Process Invocation-Request and Reply
C. Remote Process Invocation-Fire and Forget
D. Remote Call-In
Answer: A
MCQ 125. Universal Containers (UC) uses Salesforce to create and manager accounts and opportunities. With Salesforce being the master of records, the opportunities on existing accounts are required to be updated with product usage statistics from an on-premise usage tracking system that is capable of participating in contract-first integration. Which three steps should the Integration Architect consider given that UC does not want any custom development in Salesforce?
A. Create a Workflow outbound message during Opportunity creation and provide the Opportunity ID and Session ID to the remote system.
B. Use a REST API callback to update the Opportunity record with the product usage data from the remote system.
C. Create a Process Builder outbound message during Opportunity creation and provide the Opportunity ID and Session ID to the remote system.
D. Use a SOAP API callback to update the Opportunity record with the product usage data from the remote system.
E. Generate a partner WSDL in Salesforce and provide it to the remote system to create a client stu
Answer: A, D, E
MCQ 126. Universal Containers (UC) manages all of their customer information on the Sales Cloud. UC would like to view real-time order information from their ERP system, and also update the ERP system with service information from Salesforce that relates to the orders. UC's ERP system supports OData 4.0. Which two options are recommended to achieve the desired functionality?
A. Set up data replication for order and service data syncing.
B. Use an Apex callout to look up order information on the ERP system.
C. Use Salesforce connect for looking up order information from ERP.
D. Use Salesforce connect to write service data into UC's ERP syste
Answer: C, D
MCQ 127. Universal Containers wants to gather information from a third-party application to update shipping information for an order inside Salesforce. A salesperson could trigger an update and the user interface would refresh with the current status. Which are two recommended options for this when utilizing a Remote Process Invocation-Request and Reply pattern?
A. A batch Apex job that performs an Apex SOAD or HTTP callout in a synchronous manner.
B. A custom Visualforce page or button that initiates an Apex REST callout in a synchronous manner.
C. A custom Visualforce page or button that initiates an Apex SOAP callout in a synchronous manner.
D. A trigger that's invoked from Salesforce Data changes, performs and Apex SOAP in a synchronous manner
Answer: B, C
MCQ 128. Universal Containers (UC) is working with multiple partners to get lists of leads into the Lead aggregation system. These leads are imported into Salesforce as parot of a daily batch integration through the ETL tool. UC observed that may times, leads are duplicated, as they are sourced from different partners. Which two options should an Architect recommend to improve data quality?
A. Extract Salesforce lead data into a staging table and use ETL to de-duplicate.
B. Create a custom web service to identify duplicate leads and load.
C. Design an ETL job to eliminate duplicates from the lead aggregation system.
D. Use duplicate management rules on Lead to report duplicate record
Answer: C, D
MCQ 129. Universal Containers has a call center that would like to have a dashboard that updates in real time and shows information about phone calls that have been completed today (recorded in the Activity object). There are several teams in the call center, and each dashboard should only show calls from that team. An employee can start the board each morning, but after that no further user interaction should be needed. What is a recommended pattern that would minimize implementation time?
A. Develop a Visaulforce page that uses the Steaming API.
B. Use Heroku to develop a dashboard page that uses the REST API.
C. Use native Salesforce dashboard functionality
D. Develop a Visualforce page that uses JavaScript Remotin
Answer: A
Company-wise Index
Questions whose source document recorded the company that asked them. Numbers refer to the Q numbers above.
Accenture
Q36. How do you call an external web service from Salesforce?
Q88. Where do you store credentials in Salesforce?
Q149. What are the limits of future methods?
Q211. Can we call a Batch Apex job from a trigger?
Q261. How do you remove duplicates from a list of records in Apex?
Q262. What are governor limits? Can you name three examples?
Q263. Can we call external services from a trigger?
Q264. How do you delete lookup child records when the parent is deleted?
Q265. How many records can be fetched from a single SOQL transaction?
Q349. What is the difference between an External ID and a Unique ID?
Q350. Write a SOQL query to find the unique designations of employees.
Q480. Which framework does Salesforce Lightning (Aura) follow?
Q715. What is a dynamic approval process?
Q717. Will one workflow rule affect another workflow rule?
Q718. How can you convert a lead?
Q734. What are assignment rules in Salesforce?
Q813. Explain Test.setCurrentPage() (Test.setPage) in Apex tests.
Q870. What is case management in Salesforce?
Q891. Tell me about yourself.
Appcino
Q475. What is the difference between a component event and an application event in Aura?
Q565. What is view state in Visualforce?
Q566. What is the maximum view state size in Visualforce?
Q567. What is an action region in Visualforce?
Cloud 360
Q39. When should you use a platform event?
Q89. How do you give permissions to a particular user via a permission set?
Q90. What are the levels at which we can restrict a user's access to records?
Q91. What default access levels are available in the organization-wide defaults (OWD)?
Q92. In OWD there are three columns - internal user, external user and guest user. If the internal user access is set to Private, can the external user have Read/Write access?
Q93. Scenario: how do you give a specific user permission on a particular object?
Q94. What happens if one profile has Read/Write access and another has Write/Delete access on the same object?
Q205. Where do you use Database.AllowsCallouts?
Q206. How many methods are there in a schedulable class?
Q207. How many methods are there in a Queueable class?
Q269. What is the global access modifier used for in Apex?
Q292. What is the difference between break and continue in an Apex for loop?
Q351. How do you find duplicate values using an index?
Q447. What are the phases in component event propagation?
Q483. What are the navigate-to-URL methods in Lightning Aura?
Q484. How do you redirect to another URL from a JavaScript controller?
Q485. If a child component fires an event with a value X, does it go to the parent component or to the super parent component?
Q486. How do you expose a component to a community using interfaces?
Q568. In a PageReference, what is the difference between setRedirect(true) and setRedirect(false)?
Q569. If a Visualforce page has multiple extensions with methods of the same name, which method is called?
Q638. In Data Loader, what is the difference between Export and Export All?
Q719. In which scenario do we prefer to use Custom Settings?
Q720. In which scenario do we prefer to use Custom Metadata Types?
Q803. Which important file is required to deploy a community?
Cognizant
Q8. Do you have an exception handling framework? How does it work?
Q9. How do you handle a one-time data migration of a huge number of records (lakhs of records)?
Q18. How does MuleSoft integrate with Salesforce?
Q37. How will you handle a huge volume of data in an integration?
Q38. Why would you use MuleSoft instead of Heroku - what is the difference?
Q266. What are the best practices for writing a trigger?
Q267. Can you give an example of bulkifying code?
Q268. What is the main aim of bulkifying code?
Q327. What is the order of execution when a record is saved in Salesforce?
Q479. What is the life cycle of an event in Salesforce Lightning (Aura)?
Q480. Which framework does Salesforce Lightning (Aura) follow?
Q481. What are design attributes in Aura?
Q482. What are the interfaces available in an Aura component?
Q801. Which CI/CD tool do you use?
Q802. Which Git commands have you used?
Q871. What is the life cycle of Sales Cloud and which objects are used in it?
Q872. Are you using the Lead object or the Opportunity object, and why do we use the Opportunity object instead of the Lead object?
Q896. Explain the most challenging module you have worked on.
Q897. Which cloud have you worked on?
GenPact
Q34. Have you worked on Platform Events? What are they?
Q35. Have you worked on REST APIs?
Q36. How do you call an external web service from Salesforce?
Q87. How do you handle the authentication part in Salesforce?
Q131. Can we call a future method from Batch Apex?
Q148. Can we call one future method from another future method?
Q204. How many future methods can we write in a class?
Q476. How do you display accounts and their related contacts in an Aura component using custom code?
Q477. What is the difference between a JavaScript controller and a JavaScript helper in an Aura component?
Q478. A component is working very slowly - how do you improve its performance?
Q713. Scenario: how do you send a notification to the seniors (managers) on an Opportunity?
Q714. How do you use record types to create picklists?
Q895. What do you do on a daily basis?
Mahindra & Mahindra
Q86. How do you give a user permission to access an Aura component?
Q202. What is the difference between batch Apex, future methods and queueable Apex?
Q203. Can you give an example of Queueable Apex?
Q259. What do you do when a governor limit is hit? How do you rectify it?
Q260. What do you do if a SOQL query returns more than 50,000 records?
Q473. How do you trace where a section (for example a quick action) on a Lightning page comes from?
Q474. What is the use of the doInit method in an Aura component?
Q869. What is a Partner Community in Salesforce?


