salesforce basic interview questions
1. What are trigger best practices?

Trigger best practices include below things
Avoid DML, SOQLs in triggers
1. Have one trigger per object
2. Have a helper class to hold the logic of the trigger
3. Avoid recursion

2. Give one example where you will use a trigger instead of a workflow?

Answer:- Workflow allows us to perform certain operation on only one object but if we required performing operations/tasks/updates on multiple objects then we use trigger instead of workflows.

3. What is the difference between custom controller and extension in salesforce?

Custom Controller: A custom controller is an Apex class that implements all of the logic for a page without leveraging a standard controller. Use custom controllers when you want your Visualforce page to run entirely in system mode, which does not enforce the permissions and field-level security of the current user.

Controller extension: A controller extension is an Apex class that extends the functionality of a standard or custom controller. Use controller extensions when:

• You want to leverage the built-in functionality of a standard controller but override one or more actions, such as edit, view,save,or delete.

• You want to add new actions.

• You want to build a Visualforce page that respects user permissions. Although a controller extension class executes in system mode, if a controller extension extends a standard controller, the logic from the standard controller does not execute in system mode. Instead, it executes in user mode, in which permissions, field-levelsecurity, and sharing rules of the current user apply.

A controller extension is any Apex class containing a constructor that takes a single argument of type ApexPages.StandardController or CustomControllerName, WhereCustomControllerName is the name of a custom controller you want to extend.

Note: Although custom controllers and controller extension classes execute in system mode and thereby ignore user permissions and field-levelsecurity,you can choose whether they respect a user's organization-wide defaults, role hierarchy, and sharing rules by using the with sharing keywords in the class definition.

4. Wrapper Class in Apex Salesforce: Wrapper class is collections of different data type, subject etc.

In following example we are bind Account, Opportunity standard object. We query and perform business logic on the Collection of elements across unrelated objects with the custom data type.
VisualForce Page:
< apex:page controller="wrapperDemoCtrl" >
< apex:pageBlock title="Account From wrapper Class">
< apex:pageBlockTable value="{!wraccount}" var="wra">
< apex:column value="{!wra.acc.Name}"/>
< /apex:pageBlockTable>
< /apex:pageBlock>
< apex:pageBlock title="Opportunity From wrapper Class">
< apex:pageBlockTable value="{!wraoppn}" var="wropp">
< apex:column value="{!wropp.op.Name}"/>
< /apex:pageBlockTable>
< /apex:pageBlock>
< /apex:page>
Controller :
public class wrapperDemoCtrl
public list wraplist{get;set;
public list getwraccount()
listacclist=[select Id,Name from Account limit 3]; wraplist= new list(); for(Account acn:acclist)
wraplist.add(new wrapperClass(acn));
return wraplist;
public list getwraoppn()
listopplist=[select Id,Name from Opportunity limit 3]; wraplist= new list(); for(Opportunity opn:opplist )
wraplist.add(new wrapperClass(opn));
return wraplist;
public class wrapperClass
public Account acc {get;set;
public Opportunity op {get;set;
public wrapperClass(Account accn)
acc= accn;
public wrapperClass(Opportunity opn)

5. What is apex scheduler?

Apex scheduler is used to invoke Apex classes to run at specific times, first implement the Schedulable interface for the class, then specify the schedule using either the Schedule Apex page in the Salesforce user interface, or the System. Schedule method.

The Schedulable interface contains one method that must be implemented, execute. global void execute(SchedulableContext sc){}

The implemented method must be declared as global or public.

The following example implements the Schedulable interface for a class called mergeNumbers:

global class scheduledMerge implements Schedulable{

global void execute(SchedulableContext SC) {

mergeNumbers M = new mergeNumbers();

The following example uses the System.Schedule method to implement the above class. scheduledMerge m = new scheduledMerge();

String sch = '20 30 8 10 2 ?';

system.schedule('Merge Job',sch,m);

You can also use the Schedulable interface with batch Apex classes. The following example implements the Schedulable interface for a batch Apex class called batchable:

global class scheduledBatchable implements Schedulable{ global void execute(SchedulableContext sc) { batchable b = new batchable(); database.executebatch(b);

Use the SchedulableContext object to keep track of the scheduled job once it's scheduled. The SchedulableContext method getTriggerID returns the ID of the CronTrigger object associated with this scheduled job as a string. Use this method to track the progress of the scheduled job.

To stop execution of a job that was scheduled, use the System.abortJob method with the ID returned by the.getTriggerID method.

6. Write a syntax and structure of scheduler class?

    Sample class
    globalclass ScheduleDemo implements Schedulable{ globalvoid execute(SchedulableContext sc){
    BatchClass b = new BatchClass(); database.executeBatch(b);

7. What is Scheduler class in Apex?

    The Apex class which is programmed to run at pre-defined interval.

    Class must implement schedulable interface and it contains method named execute().

    There are two ways to invoke scheduler:
    1. Using UI
    2. Using System. Schedule (Schedule method of System class)
    The classes which implements interface schedulable get the button texted with “Schedule”, when user clicks on that button; new interface opens to schedule the classes which implements that interface.

    To see what happened to scheduled job, go to “Monitoring |Scheduled jobs “
    Example of scheduling:
    scheduledMerge m = new scheduledMerge();
    String sch = '20 30 8 10 2 ?';
    system.schedule('Merge Job',sch,m);
    20 represents seconds
    30 represents minutes
    8 represents hour of the day
    10 represents 10th day of month
    2 represents month of the year
    ? represents day of the month

    Write a apex code to send a email?

    Sample code snippet to send an email using apex code
    Messaging.SingleEmailMessage mail= new Messaging.SingleEmailMessage();
    String[] toAddresses = new String[]{‘’};
    mail.setSubject(‘Sample MailSubject’);
    mail.setPlainTextBody(‘Hello World!’);
    Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});

8. What are the aggregate functions supported by salesforce SOQL? Following aggregate functions are supported by salesforce SOQL

    1. SUM()
    2. MIN()
    3. MAX()
    4. COUNT()
    5. AVG()

9. Write a sample aggregate query or explain how to write a aggregate queries? The return types of Aggregate functions are always an array of AggregateResult.

    Sample Code AggregateResult[] ar = [select AVG(Amount) aver from Opportunity]; Object avgAmt = ar[0].get(‘aver’);

    272. Write a code to find the average Amount for allyour opportunities by campaign? AggregateResult[] arList = [select CampaignId, AVG(amount) from Opportunity group by CampaignId];

    for(AggregateResult ar :arList){ System.debug(‘CampaignId ’+ ar.get(‘CampaignId’)); System.debug(‘Average Amount’+ ar.get(‘expr0’));


10. What are email services in salesforce and explain how we can use them in code?

    Email services are automated processes that use apex class to process the contents, headers
    and attachment of an inbound email.

    Sample code

    Use Case: create a contact record if the inbound email subject is Create Contact and body contains contact name
    globalCreateContactFromEmailimplements Messaging.InboundEmailHandler{
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,

    Messaging.InboundEnvelop envelop){
    Messaging.InboundEmailResult res = new Messaging.InboundEmailResult(); String strToCompare = ‘Create Contact’; If(email.subject.equalsIgnoreCase(strToCompare)){
    Contact c = new Contact();

    c.LastName = email.plainTextBody();

    insert c;

    //save text attachments

    for(Messaging.InboundEmail.TextAttachment att :email.textAttachments){

    Attachment a = new Attachment();

    a.Name = att.fileName;

    a.Body = att.Blob.valueOf(att.Body);

    a.ParentId = c.Id;

    insert attachment;


    //save binary attachments

    for (Messaging.Inboundemail.BinaryAttachment bAttachment :email.binaryAttachments) {

    Attachment attachment = new Attachment();

    attachment.Name = bAttachment.fileName;

    attachment.Body = bAttachment.body;

    attachment.ParentId = c.Id;

    insert attachment;

    res.Success = true;
    return res;

11. What is the row limit for apex:dataTable and apex:pageBlockTable?

    Answer:- The data set for both apex:dataTable and apex:pageBlockTable can have up to 1000 items.

12. What is the difference between apex:pageMessages, apex:pageMessage, apex:Message and apex:Messages?

    This component displays all messages that were generated for all components on the current page, presented using the salesforce styling. This will display both salesforce generated messages as well as custom messages added to the ApexPages class

    Apex:PageMessage is a component that adds single message on the page. This is used to display custom message using the salesforce formatting

    apex:Message is used to display an error on only a specific field. It is used to allow developers to place field specific errors in specific location.

    apex:Messages is similar to apex:Message but it displays allerrors

13. How can we hard delete a record using a Apex class/by code?

    ALL ROWS key word can be used to get allthe records including records in the recycle bin. Below is the sample code to delete contact records from recycle bin

    List< Contact> dContactList=[Select ID From Contact Where IsDeleted = true limit 199 ALL ROWS]; Database.emptyRecycleBin( dContactList );

14. Write a syntax and structure of batch class?

    Sample class globalClass BatchDemo implements Database.Batchable< sObject>{

    globalDatabase.QueryLocator start(Database.BatchableContext bc){

    return Database.getQueryLocator(query);

    globalvoid execute(Database.BachableContext bc,List< sObjects> scope){
    globalvoid finish(Database.BachableContext bc){

    Below code willcallthe batch class
    BatchDemo bd = new BatchDemo();

15. What is batch apex?

    Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked at runtime using Apex.

    Need of Batch Apex: - As you all might know about the salesforce governor limits on its data. When you want to fetch thousands of records or fire DML on thousands of rows on objects it is very complex in salesforce and it does not allow you to operate on more than certain number of records which satisfies the Governor limits.

    But for medium to large enterprises, it is essential to manage thousands of records every day.

    Adding/editing/deleting them when needed.

    Salesforce has come up with a powerful concept called Batch Apex. Batch Apex allows you to handle more number of records and manipulate them by using a specific syntax.

    We have to create a global apex class which extends Database.Batchable Interface because of which the salesforce compiler will know, this class incorporates batch jobs. Below is a sample class which is designed to delete all the records of Account object (Let’s say your organization Contains more than 50 thousand records and you want to mass delete allof them). Examples:-

    globalclass deleteAccounts implements Database.Batchable {

    globalfinalString Query;

    globaldeleteAccounts(String q)




    globalDatabase.QueryLocator start(Database.BatchableContext BC)


    return Database.getQueryLocator(query);


    globalvoid execute(Database.BatchableContext BC,List scope)


    List lstAccount = new list();

    for(Sobject s :scope)


    Account a = (Account)s;



    Delete lstAccount;


    globalvoid finish(Database.BatchableContext BC)


    //Send an emailto the User after your batch completes Messaging.SingleEmailMessage mail= new Messaging.SingleEmailMessage();

    String[] toAddresses = new String[] {‘’}; mail.setToAddresses(toAddresses); mail.setSubject('Apex Batch Job is done‘); mail.setPlainTextBody('The batch Apex job processed '); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail}); }


    //This is how the batch class is called.

    id batchinstanceid = database.executeBatch(new deleteAccounts(‘select Id from Account’)); 280. What are web service callouts?

    Apex Code supports the ability to expose Apex methods as a Web service. Apex also supports the ability to invoke external web services and this will refer to as 'Callouts.' The former is involved in creating a web service that a client can invoke,while the latter is invoking an externalweb service.

16. What are wrapper classes?

    A wrapper or container class is a class, a data structure, or an abstract data type whose instances are collections of other objects.

17. How do you hide header and sidebar on visualforce page? Below is the code to hide sidebar and header

    Answer:-< apex:page showHeader="false" sidebar="false"> < /apex:page>

18. What is the difference between standard and custom controller? The standard controller is auto generated by SF for allobjects.

    Answer:-Custom controllers are written by you and do what your code tells them to do.

19. How do you read parameter in visualforce page?

    Below syntax can be used to read parameters in visualforce page < apex:inputField value="{!$CurrentPage.parameters.Paramtervalue}"/> Additionalcode:

    If you're writing a custom controller, use the ApexPages global object variable and currentPage() and getParameters() methods to get query string parameters. For example, to get the value of the name query parameter in the URL:, use the following line in your custom controller:

    String value = ApexPages.currentPage().getParameters().get('name');

    •If you're editing a page,use the $PageContext globalvariable in a merge field.

    For example, suppose you want to add the Open Activities related list to an account detail page, but instead of showing the account's activities, you want to show the activities of a specified contact. To specify the contact, the following page looks for a query string parameter for the contact's ID under the name related Id:

    < apex:page standardController="Account">

    < apex:pageBlock title="Hello {!$User.FirstName}!">

    You belong to the {!} account.
    You're also a nice person.

    < apex:detailsubject="{!account}" relatedList="false"/> < apex:relatedList list="OpenActivities"

    subject="{!$CurrentPage.parameters.relatedId}"/> < /apex:page>

    For this related list to render in a saved page,valid account and contact IDs must be specified in the URL. For example,if 001D000000HRgU6 is the account ID and 003D000000OXDIx is the contact ID,

    use the URL


    To set a query string parameter:

    • If you're writing a custom controller, use the setParameters() method with ApexPages.currentPage() to add a query parameter in a test method. For example:

    String key = 'name';

    String value = 'Caroline';



    The setParameters() method is only valid inside test methods.

    • If you're editing a page,you can either construct a URL manually: < apex:outputLink value="{!}">

    Search Google < /apex:outputLink>

    Or you can use the < apex:param> tag as a child tag to write cleaner code: < apex:outputLink value="">

    Search Google

    < apex:param name="q" value="{!}"/> < /apex:outputLink>

20. What is commandLink? Explain the usage?

    Answer:- CommandLink is a link that executes an action defined by a controller, and then refreshes the current page or navigate to the different page based on the PageReference

    variable that is returned by the action.

    commandLink component must be a child of an form component.


    < apex:commandLink action=”{!save}” value=”Save” id=”theCommandLink”/> 288. What is outputLink? Explain the usage?

    OutputLink is a link to URL. This component is rendered in HTML as an anchor tag with an href attribute. The body of the OutputLink is a text or image that displays as the link Example:

    < apex:outputLink value=”” id=”theLink”>< /outputLink>

21. How to get URL parameters in Visuaforce page? If the URL is something link this https://< salesforce instance>/apex/getQueryStringParam?

    id=001d000000B1Gj5&cid=003d000000BIjFh and if we want to read cid in our visualforce page then,

    Use: $CurrentPage.parameters.cid

    If there is a single parameter in the URL string link this Then Use:


22. How to set URL parameters in Visuaforce page?

    Setting a Query String parameter can be achieved by two ways.

    Construct a URL manually like,
    < apex:outputLink value="{!}">
    Search Google
    < /apex:outputLink>
    < apex:outputLink value=""> Search Google
    < apex:param name="q" value="{!}"/> < /apex:outputLink>

23. How to get URL parameters in APEX class? If the URL is something link this https://< salesforce instance>/apex/getQueryStringParam?

    id=001d000000B1Gj5&cid=003d000000BIjFh And if we want to read cid in our visualforce page then,
    String id = ApexPages.currentPage().getParameters().get('id'); String id = ApexPages.currentPage().getParameters().get('cid');

24. How to set URL parameters in APEX class?

    To set a URL parameter using Apex code use below syntax

    String key = 'name';
    String value = 'Caroline';

25. Explain how MVC architecture fit for Salesforce?

    Answer:- In salesforce, Apex Classes works as Controllers, Visualforce Pages works as View and Custom objects works as Model.

26. How do you do File Upload using visualforce? Below is the code sample of file upload in visualforce

    Answer:- < apex:page standardController="Document" extensions="documentExt"> < apex:messages />
    < apex:form id="theForm"> < apex:pageBlock> < apex:pageBlockSection>
    < apex:inputFile value="{!document.body}" filename="{!}"/> < apex:commandButton value="Save" action="{!save}"/>

    < /apex:form>
    < /apex:page>
    /*** Controller ***/
    public class documentExt {
    public documentExt(ApexPages.StandardController controller) { Document d = (Document) controller.getRecord();
    d.folderid = UserInfo.getUserId();//this puts it in My PersonalDocuments

27. Explain Apex Data Types Apex primitive data types include

    Answer:- • String • Blob (for storing binary data)
    • Boolean
    • Date,DateTime and Time
    • Integer,Long,Decimal,Double
    • ID ( database record identifier)
    • DateTime dt = + 1;
    • Boolean isClosed = true;
    • String sCapsFirstName = ‘Andrew’.toUpperCase(); Apex sObject Types
    Sobject (object representing a standard or custom object)
    • Account acct = new Account();//Sobject example Apex has the following types of collections
    • Lists
    • Maps
    • Sets
    • List myList = new List();
    • myList.add(12);//Add the number 12 to the list
    • myList.get(0);//Access to first integer stored in the List Enums
    • Enum (or enumerated list) is an abstract that stores one value of a finite set of specified identifiers.
    • To define an Enum,use enum keyword in the variable declaration and then define the list of values.
    • By creating this Enum,you have created a new data type called Season that can be used as any other data type.
    • public enum Season {WINTER,SPRING,SUMMER,FALL} 299. Explain Apex Variables?
    Localvariables are declared with Java-style syntax. For example:
    • Integer i= 0;
    • String str;
    • Account a;
    • Account[] accts;
    • Set s;
    • Map< ID,Account> m;

28. Explain Static Methods and Variables?

    • Class methods and variables can be declared as static. Without this keyword,the default is to create instance methods and variables.
    • Static methods are accessed through the class itself,not through an object of the class: Example:
    public class blogReaders {
    public static boolean firstScript = false;
    • Static methods are generally utility methods that do not depend on an instance. System methods are static.
    • Use static variables to store data that is shared with in the class.
    • Allinstances of the same class share a single copy of static variables.
    • This can be a technique used for setting flags to prevent recursive

29. What is the use of static variable?

    When you declare a method or variable as static, it’s initialized only once when a class is loaded.
    Static variables aren’t trmitted as part of the view state for a Visualforce page.
    Static variables are only static within the scope of the request. They are not static across the server, or across the entire organization.

30. Explain Finalvariables?

    • The finalkeyword can only used with variables. • Classes and methods are finalby default.

    • Finalvariables can only be assigned a value once.

    • When defining constants, both static and finalkeywords should be used.

    Example:public static finalInteger =47;

    303. Difference between with sharing and without sharing in salesforce

    By default, all Apex executes under the System user, ignoring all CRUD, field-level, and row-level security (that is always executes using the fullpermissions of the current user). without sharing:

    Enforcing the User’s Permissions,Sharing rules and field-levelsecurity should apply to the current user.

    For example:

    public with sharing class sharingClass {

    // Code here


    without sharing:

    Not enforced the User’s Permissions, Sharing rules and field-level security. For example:

    public without sharing class noSharing {

    // Code here


    Enforcing the current user’s sharing rules can impact:(with sharing)

    SOQL and SOSL queries – A query may return fewer rows than it would operating in system context. DML operations – An operation may fail because the current user doesn’t have the correct permissions. For example, if the user specifies a foreign key value that exists in the organization, but which the current user does not have access to.

31. Explain Class Constructors with example?

    • A constructor is a specialmethod used to create (or instantiate) an object out of a class definition.

    • Constructors never have explicit return types.

    • Constructors have the same name as the class.

    • Classes have default,no-argument,public constructor if no explicit constructors is defined.

    • If you create a constructor that takes arguments and stillwant a no-argument constructor,you must explicitly define one.

    • Constructors can be overloaded,meaning you can have multiple constructors with different parameters,unique argument lists,or signatures.

    • Constructors are called before allother methods in the class.

    For Example:

    public class TestObject2 {

    private static finalInteger DEFAULT_SIZE = 10;

    Integer size;

    //Constructor with no arguments

    public TestObject2() {

    this(DEFAULT_SIZE);// Using this(…) calls the one argument constructor


    // Constructor with one argument public TestObject2(Integer ObjectSize) { size = ObjectSize; }


    New objects of this type can be instantiated with the following code: TestObject2 myObject1 = new TestObject2(42);

    TestObject2 myObject2 = new TestObject2(); 305. Class Access Modifiers

    • Classes have different access levels depending on the keywords used in the class definition. global:this class is accessible by allApex everywhere.

    • Allmethods/variables with the webService keyword must be global.

    • Allmethods/variables dealing with emailservices must be global.

    • Allmethods/variables/inner classes that are globalmust be within a globalclass to be accessible. public:this class is visible across you application or name space.

    private:this class is an inner class and is only accessible to the outer class,or is a test class. protected: this me that the method or variable is visible to any inner classes in the defining Apex class. You can only use this access modifier for instance methods and member variables.

    To use the private,protected,public,or globalaccess modifiers,use the following syntax: [(none)|private|protected|public|global] declaration

32. Explain Variable and Method Access Modifiers in Apex?

    • Methods and variables have different levels depending on the keywords used in the declaration.
    – private: This method/variable is accessible within the class it is defined.
    – protected: This method/variable is also available to any inner classes or subclasses. It can only be used by instance methods and member variables.
    – public: This method/variable can be used by any Apex in this application namespace.
    – global: this method/variable is accessible by allApex everywhere.
    • Allmethods/variable with the webService keyword must be global.
    – The default access modifier for methods and variables is private.

33. Explain Casting in Apex?

    Apex enables casting: A data type of one class can be assigned to a data type of another class,but only if one class is a child of other class.
    • Casting converts an object from one data type to another.
    • Casting between the generic sObject type and the specific sObject type is also allowed.
    For Example:

    sObject s = new Account(); Account a = (Account)s;
    Contact c = (Contact)s //this generates a run time error.

34. Explain Exceptions Statements in Apex?

    Similar to Java, Apex uses exception to note errors and other events that disrupt script execution with the following
    Exception statement keywords:
    • Throw: signals that an error has occurred and provides an exception object.
    • Try: identifies the block of code where the exception can occur.
    • Catch: identifies the block of code that can handle a particular exception. There may be multiple catch blocks for each try block.
    • Finally: optionally identifies a block of code that is guaranteed to execute after a try block. Exception Example:
    public class OtherException extends BaseException {} Try{
    //Add code here
    throw new OtherException(‘Something went wrong here…’); } Catch (OtherException oex) {
    //Caught a custom exception type here } Catch (Exception ex){
    //Caught allother exceptions here

35. Name different Exceptions?

    All exceptions support built-in methods for returning the error message and exception type, below is the some of the Exception Methods,

    AsyncException, CalloutException , DmlException, EmailException, JSONException , ListException, MathException, NoAccessException, NoDataFoundException, NullPointerException, QueryException .

36. Explain about Salesforce annotations

    Answer:- All exceptions support built-in methods for returning the error message and exception type, below is the some of the Exception Methods,

    AsyncException, CalloutException , DmlException, EmailException, JSONException , ListException, MathException, NoAccessException, NoDataFoundException, NullPointerException, QueryException .

    36. Explain about Salesforce annotations

    Apex annotations modify the way a method or class is used. Below is the list of annotations supported by salesforce @Deprecated

    Use the deprecated annotation to identify methods, classes, exceptions, enums, interfaces, or variables that can no longer be referenced in subsequent releases of the managed package in which they reside. This is useful when you are re-factoring code in managed packages as the requirements evolve. New subscribers cannot see the deprecated elements, while the elements continue to function for existing subscribers and API integrations.


    Use the future annotation to identify methods that are executed asynchronously. When you specify future,the method executes when Salesforce has available resources.

    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 arecollected by the system. When stopTest is executed, all asynchronous processes are run synchronously.


    Use the isTest annotation to define classes or individual methods that only contain code used for testing your application. The isTest annotation is similar to creating methods declaredas testMethod.


    The @ReadOnly annotation allows you to perform unrestricted queries against the database. All other limits still apply. It's important to note that this annotation, while removing the limit of the number of returned rows for a request, blocks you from performing the following operations within the request: DML operations, calls to System.schedule,calls to methods annotated with @future, and sending emails.


    The RemoteAction annotation provides support for Apex methods used in Visualforce to be called via JavaScript. This process is often referred to as JavaScript

    remoting. @TestVisible

    Use the TestVisible annotation to allow test methods to access private or protected members of another class outside the test class. These members include methods, member variables, and inner classes. This annotation enables a more permissive access level for running tests only.

    Apex REST annotations:


    The @RestResource annotation is used at the class level and enables you to expose

    an Apex class as a REST resource.


    The @HttpDelete annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP DELETE request is sent,and deletes the specified resource.


    The @HttpGet annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP GET request is sent, and returns the specified resource.


    The @HttpPatch annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP PATCH request is sent, and updates the specified resource.


    The @HttpPost annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP POST request is sent,and creates a new resource.


    The @HttpPut annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP PUT request is sent,and creates or updates the specified resource.

37. Difference between trigger.newMap and trigger.oldMap?

    Answer:- Trigger.newMap - A map of IDs to the new versions of the sObject records. Note that this map is only available in before update,after insert,and after update triggers.

    Trigger.oldMap - A map of IDs to the old versions of the sObject records. Note that this map is only available in update and delete triggers.

38. What are the available Trigger Events? There are 6 trigger events available.

    1. Insert
    2. Update
    3. Delete
    4. Merge
    5. Upsert
    6. Undelete

39. What are the available Trigger contest variables? Below are the list of Trigger context variables

    1. isBefore 2. IsAfter
    3. isInsert
    4. IsUpdate
    5. isDelete
    6. isUndelete
    7. isExecuting
    8. new
    9. old
    10. newMap
    11. oldMap
    12. size

40. What is IDE?

    The IDE is a powerful client application for creating, modifying, testing and deploying applications. Based on the Eclipse platform, it provides a comfortable environment for programmers familiar with integrated development environments, allowing you to code, compile, test,and deploy allfrom within the IDE itself.

41. Explain the Sequence of Salesforce Triggers and Order of Execution?

    The following is the order of salesforce execution when the you create or update a record,

    1) Loads the originalrecord from the database or initializes the record for an upsert statement.

    2) Loads the new record field values from the request and overwrites the old values.

    If the request came from a standard UI edit page, Salesforce runs system validation to check the record for:

    Required values at the layout leveland field-definition level

    Valid field formats (ex:zip code,country code format)

    Maximum field length (ex:mobile number must 10 digits)

    Salesforce doesn’t perform system validation in this step when the request comes from other sources,such as an Apex application or a SOAP API call.

    3) Run allbefore triggers.

    4) Runs most system validation steps again, such as verifying that all required fields have a non-null value, and runs any user-defined validation rules. The only system validation that Salesforce doesn’t run a second time (when the request comes from a standard UI edit page) is the enforcement of layout-specific rules.

    5) Saves the record to the database, but doesn’t commit yet.

    6) Run allafter triggers.

    7) Run assignment rules.

    8) Run auto-response rules.

    9) Run workflow rules.

    10) If there are workflow field updates, updates the record again.

    11) If the record was updated with workflow field updates, fires before and after triggers one more time (and only one more time),in addition to standard validations. Custom validation rules are not run again.

    12) Run escalation rules.

    13) If the record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Parent record goes through save procedure.

    14) If the parent record is updated, and a grand-parent record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Grand-parent record goes through save procedure.

    15) Run Criteria Based Sharing evaluation.

    16) Commits allDML operations to the database.

    17) Run post-commit logic,such as sending email.

42. What is Visualforce in Salesforce?

    Answer:- Visualforce is the component-based user interface framework for the platform. The framework includes a tag-based markup language, similar to HTML. Each Visualforce tag corresponds to a coarse or fine-grained user interface component,such as a section of a page,or a field. Visualforce boasts about 100 built-in components,and a mechanism whereby developers can create their own components.

    • Visualforce pages can react differently to different client browsers such as those on a mobile or touch screen device.

    • Everything runs on the server, so no additional client-side callbacks are needed to render a complete view.

    • Optionalserver-side callouts can be made to any Web service.

    Visualforce is a Web-based framework that lets you quickly develop sophisticated, custom UIs for desktop and mobile apps. Using native Visualforce markup and standard Web development technologies such as HTML5, CSS, JavaScript, and jQuery, you can rapidly build rich UIs for any app.

43. Let’s say we have to update the same record in After Trigger context. Is there any way or workaround?

    If we create a new instance of a sObject in the Apex Trigger in memory using the Id of the newly created record as provided in the After Trigger context, we can perform an Update DML statement and not get a read only error. This is because in Apex,the SObject is seen as a new reference (even though the records have the same SFDC ID) and therefore is eligible for DML operations. The below snippet of code illustrated this working and not working.

    List< Contact> originals = new List< Contact>(); if(mirrorResultMap.values().size() > 0)


    for(Contact origContact :contactRecs.values())


    Contact mirrorContact = mirrorResultMap.get(origContact.Id);

    //origContact.Linked_Contact__c = mirrorContact.Id; //Link the Original Record tot he Mirror Record WILL FAIL

    Contact origContactUpdate = new Contact(Id=origContact.Id, Linked_Contact__c = mirrorContact.Id);//This willWORK



    //update contactRecs.values(); //Update the Records -> THIS WILL FAIL AS ITS ORIGINAL RECORDS IN MEMORY

    update originals;


44. System.debug() statements are included against script count?

    Answer:- Any statement ending with semi-colon willbe included against script count.

45. In how many ways you can invoke Controllers / Controller Extensions method from VF? We can invoke Aprex Controllers or Controller Extensions using below methods.

    • Javascript Remoting
    • ActionFunction
    • ActionSupport
    • ActionPoller

46. What is the use of apex:detailcomponent ?

    With the help of this Visualforce component, we can directly get complete behavior of page layout defined for logged in user’s profile. There is no need to add fields,related lists explicitly.

47. What is the difference between “apex:dataTable” and “apex:pageBlockTable” components in Visualforce?


    DataTable PageBlockTable
    Not required Should be defined inside pageBlock or pageBlockSection
    No styles are used Uses standard style sheets
    Not Required It has the required attribute “value”
    We need to specify Column headers will be displayed
    Column headers explicitly automatically

48. User have all the permissions to see the Dashboard and Source Folder still when he wants to see dashboard, it’s not visible. What might be the cause?

    It is possible that Salesforce User license for Dashboard running user is different than User wants to access Dashboard.

    Example – Running User license is “Salesforce” and user trying to access Dashboard is “Salesforce Platform”.

49. How to implement the pagination in SOQL?

    In spring 12, Salesforce has come up with ability of SOQL to get records from position “X” instead of position “1” every time to help creating pagination feature.

    Pagination in SOQL using keyword Offset
    Select Id,Name from Lead LIMIT 5 OFFSET 2
    Above query willreturn 5 Lead records starting from record number 10 (5×2).

50. How to generate the random string or random password using Apex?

    Integer len = 10; Blob blobKey = crypto.generateAesKey(128); String key = EncodingUtil.convertToHex(blobKey); String pwd = key.substring(0,len);

51. What is dynamic binding in salesforce?

    Dynamic Visualforce bindings are a way of writing generic Visualforce pages that display information about records without necessarily knowing which fields to show. In other words, fields on the page are determined at run time,rather than compile time. This allows a developer to design a single page that renders differently for various audiences, based on their permissions or preferences. Dynamic bindings are useful for Visualforce pages included in managed packages since they allow for the presentation of data specific to each subscriber with very little coding.
    Example 1:
    Access the Account name from Contact.
    Consider Data type in Apex
    public Map< String,List< Account>> accountsMap {get;set;}
    Visualforce page:
    < apex:variable value="A" var="selectedKey" />
    < apex:pageBlockTable value="{!accountsMap[selectedKey]}" var="acc"> < apex:column value="{!}"/>
    < apex:column value="{!acc.BillingStreet}"/>
    < apex:column value="{!acc.BillingCity}"/>
    < apex:column value="{!acc.BillingPostalCode}"/>
    < /apex:pageBlockTable>

52. How to convert lead using Apex?

    Lead myLead = new Lead(LastName = 'Foo',Company='Foo Bar'); insert myLead;

    Database.LeadConvert lc = new database.LeadConvert(); lc.setLeadId(;

    LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];

    lc.setConvertedStatus(convertStatus.MasterLabel); Database.LeadConvertResult lcr = Database.convertLead(lc); System.assert(lcr.isSuccess());

53. Consider total 90k records present in Salesforce and you have used the count() method of soql. What will be output of it? (we need to verify this feature in recent versions of the salesforce api’s)

    It will throw an error something like “Too many query rows: 50001”, as the record limit in SOQL is 50,000. Although the count() returns only one row however it processes each record and thus hit the allowed governor limit.

54. How to get the Recordtype Id using Dynamic Apex?

    Normally to get the RecordtypeId for any sObject we use SOQL and it will count against your limit.

    So below method willbypass the need of SOQL Query.

    Map m = Schema.getGlobalDescribe() ; Schema.SObjectType s = m.get('API_Name_Of_SObject') ; Schema.DescribeSObjectResult cfrSchema = s.getDescribe() ; Map RecordTypeInfo = cfrSchema.getRecordTypeInfosByName(); Id rtId = RecordTypeInfo.get('Record Type Name').getRecordTypeId();

55. Write Apex code which will take the RecordID as input and on the basis of that it will print the Object name and field names of sObject.

    Answer:- List< Schema.SObjectType> gd = Schema.getGlobalDescribe().Values(); Map objectMap = new Map< String,String>(); for(Schema.SObjectType f :gd)




    String sampleId ='00390000003LIVw'; String prefix = sampleId.substring(0,3); String objectName = objectMap.get(prefix); System.debug('** SObject Name ** '+objectName); System.debug('** SObject Name ** '+objectName);

    Map< String, Schema.SObjectField> desResult = Schema.getGlobalDescribe().get(objectName).getDescribe().Fields.getMap();

    List< String> fieldList = new List< String>(); fieldList.addAll(desResult.keySet()); for(integer i=0;i< fieldList.size();i++)


    System.debug('** Field Name ** '+fieldList[i]);


56. How to get “https” link instead of “http” for Visualforce page using URLFOR() in Email Template

    When you create the Link using URLFOR() in Email Template,it creates link in “http” format instead of “https” and thus causes end user to logged into salesforce again.

    So instead of

    < a href='{ !URLFOR('/apex/SomePage', null,

    [id=Some_Object__c.Id,retURL="/apex/SomeOtherPage"])}'>Go to SomePage here! We can use something like :

    < a href='{!SUBSTITUTE(URLFOR('/apex/SomePage', null,

    [id=Some_Object__c.Id,retURL="/apex/SomeOtherPage"]),'http:','https:')}'>Go to SomePage here! 333. When you get the error “Non-selective query against large object type”? How to resolve it?

    Whenever an object has greater than 100K records any query on that object must be “selective”. For a query to be selective it must have enough indexed filters (where clauses) so that less than 10% of the records (in our example 10K) are returned before applying the limit statement.

57. In Controller extension, you are getting the error “SObject row was retrieved via SOQL without querying the requested field” while accessing the field of parent Custom Object or standard Object for which the Controller extension was written. How to resolve that?

In Constructor of the Controller extension, only Id of Custom Object is supplied. We need to query the required field explicitly in order to use in remaining part of the code.

58. Using Apex how you can determine that user is in Sandbox or production?

By using below code,we can identify the given organization is a sandbox or production.

If the code returns true then it is a sandbox else it is a production.

public Static Boolean isSandbox(){

String host = URL.getSalesforceBaseUrl().getHost(); String server = host.substring(0,host.indexOf('.'));

// It's easiest to check for 'my domain'sandboxes first

// even though that willbe rare


return true;

// tapp0 is a unique "non-cs" server so we check it now if(server == 'tapp0')

return true;

// If server is 'cs'followed by a number it's a sandbox if(server.length()>2){ if(server.substring(0,2)=='cs'){




catch(exception e){

//started with cs,but not followed by a number return false;


//cs followed by a number,that's a hit return true;



// If we made it here it's a production box

return false;


59. Consider we have overall 90% code coverage however there is one class which has 0% code coverage. Can we still able to deploy that class on production?

Yes. Minimum 1% required for every trigger and there is no such restriction for Apex class.

60. In Ajax toolkit for custom Javascript button, you have to explicitly login to API because global Session variable is not available. In that case it is security vulnerable because anybody logged in can see the javascript code and your username and password. So is there any way to avoid this?

We can create a visualforce page with output type as JavaScript. Global session variable is available in VF page.

Initialize the global javascript variable in that VF page. include VF page as a javascript file and we are done!

61. In Custom Component How we can return value to Custom Controller or Controller Extension?

In Apex,Objects are passed by reference. So supply an argument of wrapper class (object) type to custom component. If its value is changed in Custom component we will get updated value in controller also.

62. Let’s consider you had created outbound changeset previously. After that, some class is modified which is part of that old changeset. If you clone that Changeset,current updated class will be included or that previous class will be included in changset? (This need to be verified in recent versions)

Once changeset is created it cannot be modified. After creation of changset, if we modify any component it will not reflected and when we clone the changeset, all components (of course old copy of component) willbe added to changeset.

63. In trigger, let’s say we have system.debug() statement after adderror() method. Will system.debug() be statement executed in Trigger after adderror() method?

adderror() method is not error statement rather its normal execution flow and all the statements written after adderror() willbe executed normally.

64. What willhappen if you try to update record in After Trigger Context?

You willget an error saying “record is Read only”.

65. Can you use aggregate expressions inside inner query? Explanation – Can you use Group by clause inside inner query in SOQL?

Example:Something like :

SELECT Id,Name,(SELECT Count(Id),Name FROM Contacts Group By Name Havingcount(Id) > 1 ) FROM Account

No. only root queries support aggregate expressions. Return type is List< AggregateResult> for above query However the root result expects List< Account> and there is no syntax or provision available in Salesforce to specify that child results are of type “AggregateResult“.

66. What is the best way to check whether organization has PersonAccount enable or not using Apex?

Method 1:

// Test to see if person accounts are enabled. public Boolean personAccountsEnabled()




// 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:

// Check to see if person accounts are enabled. public Boolean personAccountsEnabled()


// Describe the Account object to get a map of allfields

// then check to see if the map contains the field 'isPersonAccount'

return Schema.sObjectType.Account.fields.getMap().containsKey('isPersonAccount');


67. If IE9 is not working with your custom visualforce page then how to tell your visualforce code to run in IE8 compatibility mode?

Add following metatag to pages:

< meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />

It may happen that above tips will not work as lots of time the page header already set. Then, how to achieve same result using Apex?

Add below line of code in Apex (Constructor)


68. How to display the formatted number / date in Visualforce? Which component should be used?

Use component “< apex:outputText>”. Example :Format the number into currency. < apex:outputtext value="{0,number,000,000.00}"> < apex:param value="{!valFromController}" />
< apex:outputtext value="{0,number,###,###.00}"> < apex:param value="{!valFromController}" />

69. You want to display the Encrypted field on Visualforce and you are using component apex:outputText. Willit work for Encrypted fields?

Encrypted custom fields that are embedded in the < apex:outputText> component display in clear text. The < apex:outputText> component doesn’t respect the View Encrypted

Data permission for users. To prevent showing sensitive information to unauthorized users, use the < apex:outputField> tag instead.

70. Will below query work? Explain.

SELECT COUNT(Id),Name,Address__c FROM Opportunity GROUP BY Name Above query willthrow an error.

Explanation: In Group by clause the columns selected must be either used in Group by clause or in aggregate functions. The Name field is neither used in aggregate methods and in group by clause and hence willresult in error “Malformed Query”.

71. Explain difference in COUNT() and COUNT(fieldname) in SOQL. COUNT()

COUNT() must be the only element in the SELECT list.

• You can use COUNT() with a LIMIT clause.

• You can’t use COUNT() with an ORDER BY clause. Use COUNT(fieldName) instead.

• You can’t use COUNT() with a GROUP BY clause for API version 19.0 and later. Use COUNT(fieldName) instead.


• You can use COUNT(fieldName) with an ORDER BY clause.

• You can use COUNT(fieldName) with a GROUP BY clause for API version 19.0 and later.

72. How to write the “Where” clause in SOQL when Group By is used?

We cannot use the “Where” clause with Group By instead we willneed to use the “Having Clause“. Example:Get all the opportunity where more than one record exists with same name and name contains “ABC”. SELECT COUNT(Id),Name FROM Opportunity GROUP BY Name Having COUNT(Id) > 1 AND Name like '%ABC%'

73. Let’s consider that the first component in VF page is the Datepicker. In that case whenever the page loads, salesforce auto focus the first component resulting in Datepicker onfocus event. Because of this the Datepicker component opens automatically. How we can avoid this?

On load event, write the javascript code to autofocus any other field or any other non-visible component.

Example :

< span id="focusDistraction">< /span> < script type="text/javascript">

/* prevent autopup of the date inputfield by the default focus behavoir */ window.onload=function() { document.getElementById('focusDistraction').focus();


74. How to force lead assignment rule via Apex while updating or adding the Lead?

To enforce Assignment Rules in Apex you willneed to perform following steps:

1. Instantiate the “Database.DMLOptions” class.

2. Set the “useDefaultRule” property of “assignmentRuleHeader” to True.

3. Finally call a native method on your Lead called “setOptions”, with the Database.DMLOptions instance as the argument.

// to turn ON the Assignment Rules in Apex Database.DMLOptions dmlOptn = new Database.DMLOptions(); dmlOptn.assignmentRuleHeader.useDefaultRule = true; leadObj.setOptions(dmlOptn);

75. Access custom controller-defined enum in custom component?

We cannot reference the enum directly since the enum itself is not visible to the page and you can’t make it a property.

Example: Apex class:

globalwith sharing class My_Controller { public Case currCase {get;set;}

public enum StatusValue {RED,YELLOW,GREEN} public StatusValues getColorStatus() {

return StatusValue.RED; //demo code - just return red



Visualforce page:

< apex:image url='stopsign.png'rendered="{!colorStatus == StatusValue.RED}"/>

Above code snippet will throw error something like “Save Error: Unknown property‘My_Controller.statusValue’”


Add below method in Apex Controller:

public String currentStatusValue { get{ return getColorStatus().name();}} and change Visualforce code to

< apex:image url='stopsign.png'rendered="{!currentStatusValue == 'RED'}" />

76. What is the need of “Custom Controller” in Visualforce as everything can be done by the combination of Standard Controller + Extension class.

• Sharing setting is applied on standard object/extension by default;In case we don’t want to apply sharing setting in our code then Custom controller is only option.

• It is possible that the functionality of page does not required any Standard object or may require more than one standard object,then in that case Custom controller is required.

77. In class declaration if we don’t write keyword “with sharing” then it runs in system mode then why keyword “without sharing” is introduced in apex?

Let’s take example,there is classA declared using “with sharing” and it calls classB method. classB is not declared with any keyword then by default “with sharing” will be applied to that class because originating call is done through classA. To avoid this we have to explicitly define classB with keyword “without sharing”.

78. If user doesn’t have any right on particular record and have only read level access at object level. Can he change the record owner?

Yes. In profile,there is setting for “Transfer Record”.

79. In Which Scenario share object “MyCustomObject__share” is not available/created for custom object “MyCustomObject” ?

The object’s organization-wide default access level must not be set to the most permissive access level. For custom

Objects,that is Public Read/Write.

80. How to get the picklist value in Apex class?

Using Dynamic apex, we can achieve this. On object of type pickilist, call getDescribe(). Then call the getPicklistValues() method. Iterate over result and create a list. Bind it to < apex:selectOptions>. Code Example:

Let’s say we have a custom object called OfficeLocation__c. This object contains a picklist field Country__c.

The first thing we need to do, within our controller is use the getDescribe() method to obtain information on

the Country__c field:

Schema.DescribeFieldResult fieldResult = OfficeLocation__c.Country__c.getDEscribe();

We know that Country__c is a picklist,so we want to retrieve the picklist values:

List< Schema.PicklistEntry> ple = fieldResult.gerPicklistValues();

The only thing left for us to do is map the picklist values into an < apex:selectOptions> tag can use for display. Here is the entire method from our controller to do this:

public List< SelectOption> getCountries()

{ List< SelectOption> options = new List< SelectOption>();

Schema.DescribeFieldResult fieldResult =


List< Schema.PicklistEntry> ple = fieldResult.getPicklistValues();

for( Schema.PicklistEntry f :ple)


options.add(new SelectOption(f.getLabel(),f.getValue()));


return options;


With our controller logic all complete, we can call the getCountries() method from our Visualforce page, and populate the < apex:selectList> tag:

< apex:selectList id="countries" value="{!Office_Location__c.Country__c}"

size="1" required="true">

< apex:selectOptions value="{!countries}"/>

< /apex:selectList>

81. What are the types of controller in visualforce?

There are basically two types of Controller in Visualforce page.
1. Standard Controller and
2. Need to write different SOQL for different object.
3. SOQL against same field willbe slow.
4. Custom Controller

82. How many Controllers can be used on single VF page?

Only one controller can be used salesforce. Other than them,Controller extension can be used. There may be more than one Controller extension.


< apex:page standardController="Account"

extensions="ExtOne,ExtTwo" showHeader="false">

< apex:outputText value="{!foo}" />

< /apex:page>

if ExtOne and ExtTwo,both have the method getFoo() then the method of ExtOne willbe executed. A controller extension is any Apex class that contains a constructor that takes a single argument of typeApexPages.StandardController or CustomControllerName,where CustomControllerName is the name of a custom controller that you want to extend.

83. Explain System.runAs()

DGenerally, all Apex code runs in system mode, and the permissions and record sharing of the current user are not taken into account. The system method,System.runAs(), lets you write test methods that change user contexts to either an existing user or a new user. All of that user’s record sharing is then enforced. You can only use runAs in a test method. The original system context is started again after allrunAs() test methods complete.
Example :
System.runAs(u) {

// The following code runs as user 'u' System.debug('Current User:'+ UserInfo.getUserName()); System.debug('Current Profile:'+ UserInfo.getProfileId());}

// Run some code that checks record sharing


84. Explain Test.setPage().

It is used to set the context to current page,normally used for testing the visualforce controller.

Difference between SOSL and SOQL in Salesforce ?


Stands for "Salesforce object search language". Stands for "Salesforce object query language".

Works on multiple object at a same time.

Allfields are already text indexed.

Cannot used in Triggers. Can only be used in ApexCan be used in Apex class and Triggers. class and anonymous block.

85. How to round the double to two decimalplaces in Apex? Decimald = 100/3;

Double ans = d.setScale(2) ;

86. In how many ways we can invoke the Apex class?

1. Visualforce page
2. Trigger
3. Web Services
4. EmailServices

87. Can we create Master Detailrelationship on existing records?

No. As discussed above, first we have to create the lookup relationship then populate the value on allexisting record and then convert it.

88. What is the difference between database.insert and insert? insert is the DML statement which is same as databse.insert.

However, database.insert gives more flexibility like rollback, default assignment rules etc. we can achieve the database.insert behavior in insert by using the method setOptions(Database.DMLOptions)
Important Difference:
• If we use the DML statement (insert),then in bulk operation if error occurs,the execution will stop and Apex code throws an error which can be handled in try catch block.
• If zDML database methods (Database.insert) used,then if error occurs the remaining records will be inserted / updated means partialDML operation willbe done
What is the scope of static variable?
When you declare a method or variable as static, it’s initialized only once when a class is loaded.
Static variables aren’t transmitted as part of the view state for a Visualforce page.
Static variables are only static within the scope of the request. They are not static across the server, or across the entire organization.

89. Other than SOQL and SOSL what is other way to get custom settings?

Other than SOQL or SOSL,Custom settings have their own set of methods to access the record. For example:If there is custom setting of name ISO_Country,

SO_Country__c code = ISO_Country__c.getInstance(‘INDIA’);

//To return a map of data sets defined for the custom object (all records in the custom object), //you would use:

Map< String,ISO_Country__c> mapCodes = ISO_Country__c.getAll(); // display the ISO code for India

System.debug(‘ISO Code:‘+mapCodes.get(‘INDIA’).ISO_Code__c); //Alternatively you can return the map as a list: List< String> listCodes = ISO_Country__c.getAll().values ();

90. What happens if child have two master records and one is deleted?

Child record willbe deleted.

91. What is Difference in render,rerender and renderas attributes of visualforce?

render – It works like “display” property of CSS. Used to show or hide element.
rerender – After Ajax which component should be refreshed – available on commandlink, commandbutton,actionsupport etc.
renderas – render page as pdf,doc and excel.

92. How to get the list of allavailable sobject in salesforce database using Apex (Dynamic Apex)?

Map< String,Schema.SObjectType> m = Schema.getGlobalDescribe();

93. How to create instance of sObject dynamically?

Normally the sObject is created like “Account a = new Account();”. But if you are in situation that you don’t know which sObject is going to be instantiated? Means it willbe decided at runtime,how you willhandle it?

public SObject getNewSobject(String t){

// Callglobaldescribe to get the map of string to token. Map gd = Schema.getGlobalDescribe();

// Get the token for the sobject based on the type.

Schema.SObjectType st = gd.get(t);

// Instantiate the sobject from the token. Sobject s = st.newSobject(); return s;


94. How to get all the fields of sObject using dynamic Apex?

Map< String,Schema.SObjectType> m = Schema.getGlobalDescribe() ; Schema.SObjectType s = m.get ('API_Name_Of_SObject') ; Schema.DescribeSObjectResult r = s.getDescribe() ; Map< String,Schema.SObjectField> fields = r.fields.getMap() ;

95. How to get all the required fields of sObject dynamically?

There is no direct property available in Apex dynamic API to represent the required field. However there is another way to know about it.

If any fields have below three properties then it is mandatory field.

1. If it is Creatable

2. If it is not nillable and

3. If it does not have any default value Map< String,Schema.SObjectType> m = Schema.getGlobalDescribe() ; Schema.SObjectType s = m.get(so.apiName) ; Schema.DescribeSObjectResult r = s.getDescribe() ; Map< String,Schema.SObjectField> fields = r.fields.getMap() ; for(String f :fields.keyset())


Schema.DescribeFieldResult desribeResult = fields.get(f).getDescribe(); if( desribeResult.isCreateable() && !desribeResult.isNillable() &&

!desribeResult.isDefaultedOnCreate() )


//This is mandatory / required field



96. What is property in Apex? Explain with advantages.

Apex mainly consists of the syntax from the well-known programming language Java. As a practice of encapsulation in java we declare any variable as private and then create the setters and getters for that variable.

private String name;

public void setName(String n)


name = n;


public String getName()


return name;


However,the Apex introduced the new concept of property from language C# as shown below:

public String name {get;set;}

As we can see how simple the code is and instead of using nearly 8 to 11 lines all done in 1 line only. It will be very useful when lots of member is declared in Apex class. It has another advantage in “number of lines of code” limit by salesforce which will drastically reduced.

97. What is the controller extension?

Any apex class having a public constructor with Custom Controller or Standard Controller object as a single argument is known as controller extension.

98. Explain the need or importance of the controller extension.

Controller extension is very useful and important concept introduced by the salesforce recently. It gives the power to programmer to extend the functionality of existing custom controller or standard controller.

A Visualforce can have a single Custom controller or standard controller but many controller extensions.

We can say that the custom extension is the supporter of custom or standard controller.

Consider one example: If there is one controller written and used by the multiple visualforce pages and one of them needs some extra logic. Then instead of writing that logic to controller class (Which is used by many visualforce pages) we can create a controller extension and apply to that page only.

99. How to read the parameter value from the URL in Apex?

Consider that the parameter name is “RecordType”.

String recordType = Apexpages.currentPage().getParameters().get('RecordType');

388. If one object in Salesforce have 2 triggers which runs “before insert”. Is there any way to controlthe sequence of execution of these triggers? has documented that trigger sequence cannot be predefined. As a best practice create one trigger per object and use comment blocks to separate different logic blocks. By having alllogic in one trigger you may also be able to optimize on your SOQL queries.

100. What is the difference between and trigger.old in Apex – SFDC?


Returns a list of the new versions of the sObject records

Note that this sObject list is only available in insert and update triggers

i.e., is available in before insert,after insert,before update and after update

In the records can only be modified in before triggers. Trigger.old:

Returns a list of the old versions of the sObject records

Note that this sObject list is only available in update and delete triggers.

i.e.,Trigger.old is available in after insert,after update,before delete and after update.

101. How to restrict any Trigger to fire only once?

Triggers can fire twice,once before workflows and once after workflows.
“The before and after triggers fire one more time only if something needs to be updated,If the fields have already been set to a value,the triggers are not fired again.”
public class HelperClass {
public static boolean firstRun = true;

trigger affectedTrigger on Account (before delete,after delete,after undelete) {

Trigger.old[0].addError('Before Account Delete Error');


102. What are Global variables explain with examples?

Global variables are the variables used to reference the general information about the current user or your organization on a page.

Global variables must be referenced using Visualforce expression syntax to be evaluated, for example,{!$User.Name}.
List of available global variables are as below
1. $Action
2. $Api
3. $Component
4. $ComponentLabel
5. $CurrentPage
6. $Label
7. $Label.Site
8. $ObjectType
9. $Organization
10. $Page
11. $Profile
12. $Resource
13. $SControl
14. $Setup
15. $Site
16. $User
17. $UserRole
18. $System.OriginDateTime
19. $ User.UITheme and $User.UIThemeDisplayed

103. How to create Many to Many relationships between object?

Creating Many to Many relationship in salesforce is little tricky. You cannot create this type of relationship directly. Follow below steps to create this type of relationship.
Create both objects which should be interlinked.
Create one custom object (also called as junction object), which should have auto number as unique identification and create two master relationships for both objects, no need create tab for this object.
Now on both objects, add this field as related list.

104. In which sequence Trigger and automation rules run in The following is the order salesforce logic is applied to a record.

1. Old record loaded from database (or initialized for new inserts)
2. New record values overwrite old values
3. System Validation Rules
4. AllApex “before” triggers (EE / UE only)
5. Custom Validation Rules
6. Record saved to database (but not committed)
7. Record reloaded from database
8. AllApex “after” triggers (EE / UE only)
9. Assignment rules
10. Auto-response rules
11. Workflow rules
12. Escalation rules
13. Parent Rollup Summary Formula value updated (if present)
14. Database commit
15. Post-commit logic (sending email)
Additionalnotes:There is no way to controlthe order of execution within each group above.

105. What is S-Control?

S-Controls are the predominant widgets which are completely based on Javascript. These are hosted by salesforce but executed at client side. S-Controls are superseded by Visualforce now.

106. What is a Visualforce Page?

Visualforce is the new markup language from salesforce, by using which, We can render the standard styles of salesforce. We can still use HTML here in Visualforce. Each visualforce tag always begins with “apex” namespace. All the design part can be acomplished by using Visualforce Markup Language and the business logic can be written in custom controllers associated with the Page.

107. Will Visualforce still supports the merge fields usage like S-control?

Just like S-Controls,Visualforce Pages support embedded merge fields,like the {!$User.FirstName} used in the example.

108. What are Merge fields? Explain with example?

Merge fields are fields that we can put in Email templates, mail merge templates, custom link or formula fields to incorporate values from a record. Example:{!CustomObject.FieldName__c}

109. Where to write Visualforce code? You can write the code basically in 3 ways.

1. setup->App Setup->Develop->Pages and create new Visulaforce page.
2. Setup -> My Personal Information -> Personal Information -> Edit check the checkbox development mode. When you run the page like this, will find the Page editor at the bottom of the page. You can write you page as well as the controller class associated with it,there itself.
3. Using Eclipse IDE you can create the Visulaforce page and write the code.

110. What is difference in ISNULL and ISBLANK?

• Determines if an expression is null (blank) and returns TRUE if it is. If it contains a value, this function returns FALSE.

• Text fields are never null, so using this function with a text field always returns false. For example, the formula field IF(ISNULL(new__c) 1,0) is always zero regardless of the value in the New field. For text fields, use the ISBLANK function instead.

• Multi-select pick list fields are never null in s-controls, buttons, and email templates, so using this function with a multi-select picklist field in those contexts always returns false.
• Choose Treat blank fields as blanks for your formula when referencing a number, percent, or currency field in an ISNULL function. Choosing Treat blank fields as zeroes gives blank fields the value of zero so none of them will be null.
• Merge fields can be handled as blanks, which can affect the results of components like s-controls because they can call this function.
• When using a validation rule to ensure that a number field contains a specific value, use the ISNULL function to include fields that do not contain any value. For example, to validate that a custom field contains a value of ’1,’use the following validation rule to display an error if the field is blank or any other number: OR(ISNULL(field__c),field__c< >1)
• Determines if an expression has a value and returns TRUE if it does not. If it contains a value,this function returns FALSE.
• Use ISBLANK instead of ISNULL in new formulas. ISBLANK has the same functionality as ISNULL, but also supports text fields. will continue to support ISNULL,so you do not need to change any existing formulas.
• A field is not empty if it contains a character, blank space, or zero. For example, a field that contains a space inserted with the spacebar is not empty.
• Use the BLANKVALUE function to return a specified string if the field does not have a value; use the ISBLANK function if you only want to check if the field has a value.
• If you use this function with a numeric field, the function only returns TRUE if the field has no value and is not configured to treat blank fields as zeroes.

111. How to schedule a class in Apex?

To invoke Apex classes to run at specific times, first implement the Schedulable interface for the class, then specify the schedule using either the Schedule Apex page in the Salesforce user interface,or the System.schedule method.
After you implement a class with the Schedulable interface, use the System.Schedule method to execute it. The scheduler runs as system:allclasses are executed,whether the user has permission to execute the class or not.
The System.Schedule method takes three arguments: a name for the job, an expression used to represent the time and date the job is scheduled to run,and the name of the class.
Salesforce only adds the process to the queue at the scheduled time. Actual execution may be delayed based on service availability. The System.Schedule method uses the user's time zone for the basis of allschedules. You can only have 25 classes scheduled at one time.
Example Code:
String CRON_EXP = '0 0 * * * ?';
clsScheduledHourly sch = new clsScheduledHourly(); system.schedule('Hourly Sync',CRON_EXP,sch);
What are different APIs in

REST API provides a powerful, convenient, and simple REST-based Web services interface for interacting with Salesforce. Its advantages include ease of integration and development,and it’s an excellent choice of technology for use with mobile applications and Web projects. However, if you have a large number of records to process, you may wish to use Bulk API, which is based on REST principles and optimized for large sets of data.
SOAP API provides a powerful, convenient, and simple SOAP-based Web services interface for interacting with Salesforce.You can use SOAP API to create,retrieve,update,or delete records. You can also use SOAP API to perform searches and much more. Use SOAP API in any language that supports Web services.
For example, you can use SOAP API to integrate Salesforce with your organization’s ERP and finance systems, deliver real-time sales and support information to company portals, and populate criticalbusiness systems with customer information.
Chatter API:
Chatter API is a REST API that provides programmatic access to Chatter feeds and social data such as users, groups, followers, and files. It's used by developers who want to integrate Chatter into a variety of applications such as mobile applications,intranet sites,and third-party Web applications. Chatter API is similar to APIs offered by other companies with feeds,such as Facebook and Twitter. Its advantages include ease of integration and development.
Bulk API:
Bulk API is based on REST principles and is optimized for loading or deleting large sets of data. You can use it to query, insert, update, upsert, or delete a large number of records asynchronously by submitting batches which are processed in the background by Salesforce.
SOAP API, in contrast, is optimized for real-time client applications that update small numbers of records at a time. Although SOAP API can also be used for processing large numbers of records, when the data sets contain hundreds of thousands of records,it becomes less practical. Bulk API is
designed to make it simple to process data from a few thousand to millions of records.
The easiest way to use Bulk API is to enable it for processing records in Data Loader using CSV files. This avoids the need to write your own client application.
Metadata API:
Use Metadata API to retrieve,deploy,create,update,or delete customizations for your organization. The most common use is to migrate changes from a sandbox or testing organization to your production environment. Metadata API is intended for managing customizations and for building tools that can manage the metadata model,not the data itself.
The easiest way to access the functionality in Metadata API is to use the IDE or Migration Tool. These tools are built on top of Metadata API and use the standard Eclipse and Ant tools respectively to simplify the task of working with Metadata API. Built on the Eclipse platform, the IDE provides a comfortable environment for programmers familiar with integrated development environments, allowing you to code, compile, test, and deploy all from within the IDE itself. The Migration Tool is ideal if you want to use a script or a command-line utility for moving metadata between a localdirectory and a Salesforce organization.
Streaming API:
Use Streaming API to receive notifications for changes to data that match a SOQL query that you define.
Streaming API is useful when you want notifications to be pushed from the server to the client. Consider Streaming API for applications that poll frequently. Applications that have constant polling action against the Salesforce infrastructure, consuming unnecessary API call and processing time, would benefit from this API which reduces the number of requests that return no data. Streaming API is also ideal for applications that require general notification of data changes. This enables you to reduce the number of API calls and improve performance.
Use Apex REST API when you want to expose your Apex classes and methods so that external applications can access your code through REST architecture. Apex REST API supports both OAuth 2.0 and Session ID for authorization.
Use Apex SOAP API when you want to expose your Apex methods as SOAP Web service APIs so that external applications can access your code through SOAP. Apex SOAP API supports both OAuth 2.0 and Session ID for authorization.

112. How to display error message on Visualforce page?

In the Visualforce page add the tag:
< apex:pageMessages />

In the controller class add the error message where required
if ( requiredFieldName == null){
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Please
enter a value in the Required Field'));

113. What is Visualforce View State? And what are best practices to reduce the view state size?

Visualforce pages that contain a form component also contain an encrypted,hidden form field that encapsulates the view state of the page. This view state is automatically created, and as its name suggests, it holds the state of the page – state that includes the components, field values and controller state.

Best Practices to reduce the view state size

• Minimize number of form on a page. Use apex:actionRegion instead of using 2 or more forms.

• Refine your SOQL to only retrieve the data needed by the page.

• All public and private data members present in Standard, Custom and Controller extensions are saved.

• Mark any Apex variables that are not necessary to the view state as Transient. (The transient variables are not passed to view state and therefore not stored in View State)

• Create wizards with as few pages as possible

• Use outputLink components instead of commandLink or commandButton components where possible as they don’t need to be nested in a form.

114. What are custom settings?

Custom settings are similar to custom objects and enable application developers to create custom sets of data, as well as create and associate custom data for an organization, profile, or specific user. All custom settings data is exposed in the application cache, which enables efficient access without the cost of repeated queries to the database. This data can then be used by formula fields, validation rules,Apex,and the SOAP API.
There are two types of custom settings:
List Custom Settings
A type of custom setting that provides a reusable set of static data that can be accessed across your organization. If you use a particular set of data frequently within your application, putting that data in a list custom setting streamlines access to it. Data in list settings does not vary with profile or user, but is available organization-wide. Because the data is cached, access is low-cost and efficient:you don't have to use SOQL queries that count against your governor limits.
Hierarchy Custom Settings
A type of custom setting that uses a built-in hierarchical logic that lets you “personalize” settings for specific profiles or users. The hierarchy logic checks the organization, profile,and user settings for the current user and returns the most specific, or “lowest,” value. In the hierarchy, settings for an organization are overridden by profile settings,which,in turn, are overridden by user settings.

115. What is APEX?

It is the in-house technology of which is similar to Java programming with object oriented concepts and to write our own custom logic.

• Apex is a proceduralscripting language in discrete and executed by the platform.

• It runs natively on the Salesforce servers, making it more powerful and faster than non-server code,such as JavaScript/AJAX.

• It uses syntax that looks like Java

• Apex can written in triggers that act like database stored procedures.

• Apex allows developers to attach business logic to the record save process.

• It has built-in support for unit test creation and execution.

Apex provides built-in support for common platform idioms,including:

• Data manipulation language (DML) calls, such as INSERT, UPDATE, and DELETE, that include built-in DmlException handling

• Inline Salesforce Object Query Language (SOQL) and Salesforce Object Search Language (SOSL) queries that return lists of sObject records

- Looping that allows for bulk processing of multiple records at a time - Locking syntax that prevents record update conflicts

- Custom public API calls that can be built from stored Apex methods

- Warnings and errors issued when a user tries to edit or delete a custom object or field that is referenced by Apex

Note:Apex is included in Unlimited Edition,Developer Edition,Enterprise Edition,and Apex vs. Java:Commonalities

• Both have classes,inheritance,polymorphism,and other common OOP features.

• Both have the same name variable,expression,and looping syntax.

• Both have the same block and conditionalstatement syntax.

• Both use the same object,array,and comment notation.

• Both are compiled,strongly-typed,and transactional.

• Apex runs in a multi-tenant environment and is very controlled in its invocation and

governor limits. • To avoid confusion with case-insensitive SOQL queries, Apex is also case-insensitive.

• Apex is on-demand and is compiled and executed in cloud.

• Apex is not a general purpose programming language, but is instead a proprietary language used for specific business logic functions.

• Apex requires unit testing for development into a production environment. 409. Explain the Apex Data Manipulation Language (DML) Operations?

Use data manipulation language (DML) operations to insert,update,delete,and restore data in a database.

You can execute DML operations using two different forms:

Apex DML statements,such as:


Apex DML database methods,such as:

Database.SaveResult[] result = Database.Insert(SObject[])

While most DML operations are available in either form, some exist only in one form or the other.

The different DML operation forms enable different types of exception processing:

• Use DML statements if you want any error that occurs during bulk DML processing to be thrown as an Apex exception that immediately interrupts control flow (by using try. . .catch blocks). This behavior is similar to the way exceptions are handled in most database procedural languages.

• Use DML database methods if you want to allow partial success of a bulk DML operation—if a record fails, the remainder of the DML operation can still succeed. Your application can then inspect the rejected records and possibly retry the operation. When using this form,you can write code that never throws DML exception errors. Instead, your code can use the appropriate results array to judge success or failure. Note that DML database methods also include a syntax that supports thrown exceptions, similar to DML statements

Java Script Interview Questions

116. How can we pass javascript variable to apex class?

VF Page (Use assign input variable to VF using $Component.FieldId)

< apex:page controller="Js_Test_Class">

< apex:form>

< script>

function setVal()


document.getElementById("{!$Component.hdnField}").value = "TestValue";


< apex:inputHidden id="hdnField" value="{!theValue}" />

< apex:commandButton value="Post Page" action="{!post}" />

< script>


< /script>

Controller (Declare setter and getter for the variable being used in VF page)

public class Js_Test_Class {

public String theValue { get;set;}
public void post() {

System.Debug('The value is :'+ theValue);



117. Is it possible to call apex method in javascript code? If yes,explain?

Yes, we can call apex methods using javascript. We can achieve this using ActionFunction. ActionFunction allow you to tie an apex method to a javascript function name and invoke synchronously. ActionFunction must be a child of apex:form component. Example VF Page

< apex:page controller="t">

< script>

function myJavascriptFunc()
alert('Entered Javascript') ;

CallApexMethod() ;


< apex:form >

< apex:actionFunction name="CallApexMethod" action="{!myActionInController}"

onComplete="alert('After apex method') ;"/>

< apex:pageBlock >

< apex:pageBlockButtons>

< apex:commandButton value="Hit Me" onclick="myJavascriptFunc() ;"/>

< /apex:pageBlock>

< /apex:form>

< /apex:page>

Example Controller

public class t

public PageReference myActionInController(){

return null;



118. How to use actionFunction,actionSupport and actionPollar in salesforce?

actionFunction : provides support for invoking controller action methods directly from JavaScript code using an AJAXrequest Used when we need to perform similar action on various events. Even though, you can use it in place of actionSupport as wellwhere only event is related to only one control.
actionFunction: provides support for invoking controller action methods directly from JavaScript code using an AJAXrequest
< apex:page controller="exampleCon">
< apex:form>
< apex:actionFunction name="sayHello" action="{!sayHello}" rerender="out" status="myStatus"/>

< apex:outputPanelid="out">
< apex:outputText value="Hello "/>
< apex:actionStatus startText="requesting..." id="myStatus">
< apex:facet name="stop">{!username}< /apex:facet>
< /apex:actionStatus>
< /apex:outputPanel>
< script>window.setTimeout(sayHello,2000)< /script> < p>< apex:outputText value="Clicked? {!state}" id="showstate" />

< apex:outputPanelonclick="methodOneInJavascript('Yes!')" styleClass="btn">
Click Me
< /apex:outputPanel>
< apex:form>
< apex:actionFunction action="{!methodOne}" name="methodOneInJavascript" rerender="showstate">
< apex:param name="firstParam" assignTo="{!state}" value="" />
< /apex:actionFunction>
< /apex:form>
< /apex:page>
/*** Controller ***/
public class exampleCon {
String uname;
public String getUsername() {
return uname;
public PageReference sayHello() {
uname = UserInfo.getName();
return null;
public void setState(String n) {
state = n;
public String getState() {
return state;
public PageReference methodOne() {
return null;
private String state = 'no';
ActionSupport: A component that adds AJAX support to another component, allowing the component to be refreshed asynchronously by the server when a particular event occurs,such as a button click or mouseover.
Used when we want to perform an action on a particular event of any control like onchange of any
text box or picklist.
< apex:page controller="exampleCon">
< apex:form>
< apex:outputpanelid="counter">
< apex:outputText value="Click Me!:{!count}"/>
< apex:actionSupport event="onclick"
rerender="counter" status="counterStatus"/>
< /apex:outputpanel>
< apex:actionStatus id="counterStatus"
startText=" (incrementing...)"
stopText=" (done)"/>
< /apex:form>
< /apex:page>
/*** Controller:***/
public class exampleCon {
Integer count = 0;
public PageReference incrementCounter() {
return null;
public Integer getCount() {
return count;
ActionPolor: A timer that sends an AJAX update request to the server according to a time interval that you specify. The update request can then result in a full or partial page update. You should avoid using this component with enhanced lists.
Used when we want to perform an action on server again and again for a particular time interval.

< apex:page controller="exampleCon">
< apex:form>
< apex:outputText value="Watch this counter:{!count}" id="counter"/>
< apex:actionPoller action="{!incrementCounter}" rerender="counter" interval="15"/>
< /apex:form>
< /apex:page>
/*** Controller:***/
public class exampleCon {
Integer count = 0;
public PageReference incrementCounter() {
return null;

119. What is the difference between actionFunction and actionSupport tags?


SlNo ActionSupport ActionFunction
1) Directly call action method without javascript It can be used to call action method on single event
2) Call action method from javascript with AJAX It cannot be called from javascript function. invoke controller action methods from other Visualforce components
3) It can be used to call action method on different event It defines a new JavaScript function which can then be called from within a block of JavaScript code.

120. While trying to access javascript code from some CDN like Google, we get error something like “attempt to run uG request”. How to resolve it?

While providing URL,do not specify the protocol. Use like this:

< script type='text/javascript'src='// .js'>< /script>

121. Explain ActionFunction,ActionSupport and ActionPoller in Visualforce.

ActionFunction : This component helps to invoke AJAX request (Call Controllers method) directly from Javascript method. It must be child of apex:form.
ActionSupport : This component adds Ajax request to any other Visualforce component. Example: Commandlink button has inbuilt AJAX functionality however few components like OutputPanel does not have inbuilt AJAX capabilities. So with the help of this component, we can enable AJAX.
ActionPoller : This is timer component which can send AJAX request on pre- defined interval.
Minimum interval is 5 sec and default is 60 sec.

122. How to get selected records ID from List View using Javascript / Ajax Toolkit, when custom button is added on List View page?

Create a new Button on Lead of type List Button. Add the button on Lead List View Layout and write below Javascript code:


var recordsSelected = {!GetRecordIds($ObjectType.Lead)} for(var i=0;i< recordsSelected .length ;i++) {

alert('Selected ID '+recordsSelected[i]);


123. How to show loading image while Ajax call in Visualforce? OR how to show image in < apex:actionStatus> tag in Visualforce?

< div style="position:absolute;top:20px;left:50%;"> < apex:actionStatus id="refreshContent" >

< apex:facet name="start" >

< apex:image url="{!$Resource.LoadingImage}" /> < /apex:facet>

< /apex:actionStatus>

< /div>

124. Onchange event does not work with < apex:actionsupport> in IE9. How to resolve this error?

If we add the Header on Visualforce page then it creates lots of problem in IE9. I think there are few java-script library loaded by Header of Salesforce which makes IE9 compatible. So the best solution is to enable the Header by using “showHeader=true” in Apex page.

Integration Questions:
125. What is the default timeout period while calling webservice from Apex?

10 sec.

126. A single Apex transaction can make how many callouts to an HTTP request or an API call?

Maximum 10 callouts

127. How to increase timeout while calling web service from Apex?

docSample.DocSamplePort stub = new docSample.DocSamplePort(); stub.timeout_x = 2000;// timeout in milliseconds