SF Q & A
SF Q & A
SF Q & A
1. What is Apex Ans: It is the in-house technology of salesforce.com which is similar to Java
programming with object oriented concepts and to write our own custom logic.
2. What is S-Control ?
Ans: S-Controls are the predominant salesforce.com widgets which are completely based on
Javascript. These are hosted by salesforce but executed at client side. S-Controls are superseded
by Visualforce now.
4. Will Visual force still supports the merge fields usage like S-control ?
Ans: Yes. Just like S-Controls, Visualforce Pages support embedded merge fields, like the
{!$User.FirstName} used in the example.
Governor limits are runtime limits enforced by the Apex runtime engine. Because Apex runs in a
shared, multitenant environment, the Apex runtime engine strictly enforces a number of limits
to ensure that code does not monopolize shared resources. Types of limits that Apex enforces
are resources like memory, database resources, number of script statements to avoid infinite
loops, and number of records being processed. If code exceeds a limit, the associated governor
issues a runtime exception.
https://jitendrazaa.com/blog/webtech/salesforce/how-to-create-s-control-in-salesforce/
https://jitendrazaa.com/blog/webtech/salesforce/how-to-host-s-control-in-visualforce-page/
https://jitendrazaa.com/blog/webtech/salesforce/difference-between-sandbox-and-developer-
edition-in-salesforce/
https://jitendrazaa.com/blog/webtech/salesforce/backup-the-salesforce-data/
Ans : Governor limits do apply to all Salesforce instances (trial, developer, production or
sandbox environments). However code coverage and successful execution of test classes is only
enforced when deploying to a production environment.
3|P a g e
ISNULL:
• 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 picklist 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.
• Empty date and date/time fields always return true when referenced in ISNULL functions.
• 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)
ISBLANK:
• 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. Salesforce.com 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.
You can add, edit, or delete Apex using the Salesforce.com user interface only in a Developer
Edition organization, a Salesforce.com Enterprise Edition trial organization,
or sandboxorganization. In a Salesforce.com production organization, you can only make
changes to Apex by using the Metadata API ,
4|P a g e
13. When you can’t add Time dependent action in Workflow rule?
You can’t add time-dependent actions to a rule if you choose Every time a record is created or
edited.
1. Text
2. HTML with Letter Head
3. Custom HTML
4. Visual force
Roll up summary field in salesforce calculates the Count, Sum, Min or Max of particular field
of any child record. Thus, we can say that Roll up summary field can only be created
on Master object. To read further, please check this URL
5|P a g e
If the Account is deleted then Contact, Opportunity will also be deleted from Salesforce which
are related to that Account.
From the database perspective, check below image of child relationships of Account:
Ans :
1. Master Detail
2. Many to Many
3. Lookup
4. Hierarchical (It is available only on User Object, we cannot create this relationship)
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 one custom object (also called as junction object), which should have autonumber as
unique identification and create two master relationships for both objects, no need create
tab for this object.
7|P a g e
1. Old record loaded from database (or initialized for new inserts)
2. New record values overwrite old values
3. System Validation Rules
4. All Apex “before”• triggers
5. Custom Validation Rules
6. Record saved to database (but not committed)
7. Record reloaded from database
8. All Apex “after”• triggers
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)
Additional notes: There is no way to control the order of execution within each group
above.
21. If one object in Salesforce have 2 triggers which runs “before insert”. Is there
any way to control the sequence of execution of these triggers?
Ans : As per now, salesforce does not allow to delete any user, however you can deactivate the
user.
8|P a g e
Ans : To delete the Users Data go to Setup | Administration Setup | Data Management | Mass
Delete Record, from there select the objects like Account, Lead etc and in criteria select the users
name and delete all records of that user related to particular object.
24. How to restrict the user to see any record, lets say opportunity?
Ans : set up opportunity sharing to be private. If both users are admins or have view all records
on opportunity, then that overrides private sharing.
25. What is the difference between trigger.new and trigger.old in Apex – SFDC?
Ans :
Trigger.new :
Note that this sObject list is only available in insert and update triggers, and the records can only
be modified in before triggers.
Trigger.old :
Note that this sObject list is only available in update and delete triggers.
9|P a g e
26. How to restrict any Trigger to fire only once OR how we can avoid repeated or
multiple execution of Trigger?
Ans:
Triggers can fire twice, once before workflows and once after workflows, this is documented at
http://www.salesforce.com/us/developer/docs/apexcode/ Content/
apex_triggers_order_of_execution.htm:
“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.”
Workaround:
Add a static boolean variable to a class, and check its value within the affected triggers.
27. What is difference between WhoId and WhatId in the Data Model of Task ?
Ans :
28. Where is the option of the report for the “Custom Object with related object”
and what are the condition to generate related reports?
Ans :
If the parent object is the standard object provided by the salesforce like “Account”, “Contact”
then the report will be in there section with related custom object.
If both objects are the custom then the report will be in “Other Reports” Sections.
29. How you can provide the User Login (Authentication) in Public sites created by
Salesforce.
Answer : We can provide the authentication on public sites using “Customer Portal”.
31 : How to get the list of all available sobject in salesforce database using Apex
(Dynamic Apex)?
Ans:
1. If it is Creatable
2. If it is not nillable and
3. If it does not have any default value
12 | P a g e
<apex:pageMessages ></apex:pageMessages>
8 return name;
9}
However, the Apex introduced the new concept of property from language C# as shown below:
String recordType =
1
Apexpages.currentPage().getParameters().get('RecordType');
40. What is Master Detail relationship and look up relationship in Salesforce?
Ans:
Master Detail relationship is the Parent child relationship. In which Master represents
Parent and detail represents Child. If Parent is deleted then Child also gets deleted. Rollup
summary fields can only be created on Master records which will calculate the SUM, AVG, MIN
14 | P a g e
1. Visualforce page
2. Trigger
3. Web Services
4. Email Services
43. Can we create Master Detail relationship on existing records?
Ans:
No. As discussed above, first we have to create the lookup relationship then populate the value
on all existing record and then convert it.
44. How validation rules executed? is it page layout / Visualforce dependent?
Ans :
The validation rules run at the data model level, so they are not affected by the UI. Any record
that is saved in Salesforce will run through the validation rules.
• 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 DML database methods (Database.insert) used, then if error occurs the remaining records will
be inserted / updated means partial DML operation will be done.
47. Other than SOQL and SOSL what is other way to get custom settings?
Ans:
Other than SOQL or SOSL, Custom seting have there own set of methods to access the record.
For example : if there is custom setting of name ISO_Country,
48. What happen if child have two master records and one is deleted?
Ans :
Child record will be deleted.
50. What is Scheduler class in Apex and explain how to use Crone statement to
Schedule Apex class?
Ans:
The Apex class which is programed to run at pre defined interval.
Class must implement schedulable interface and it contains method named execute().
There are two ways to invoke schedular :
1. Using UI
2. Using System.schedule
16 | P a g e
The class 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 :
Note : Salesforce only accepts integer in Seconds and Minutes. So, lets say if you want to run
Apex job on every 10 minutes, crone statement will be ‘0 0/10 * 1/1 * ? *’ and salesforce will
throw an error saying “System.StringException: Seconds and minutes must be specified as
integers“. That mean like Time based Workflow, minimum interval to schedule job is 1 hour.
Additionally, if you have an external ID field, the field becomes searchable in the sidebar search.
You also can use the upsert API call with the extenal ID to refer to records.
You can have multiple records with the same external ID (though it is not reccomended, as it
will defeat the purpose of the external id) .
Unique ID field
This is a setting for the field that will prevent you from using the same value in multiple records
for the unique field. So if I create a 5 character text field and make it unique, and I create a
record with the value “12345” i will not be able to create another record with that same value in
the unique field. If i try to do so, I will get an error saying that the value is already in use.
Often, External Ids are set with the unique property so that the IDs will be unique to each
record.
Only one controller can be used salesforce. Other than them, Controller extension can be
used. There may be more than one Controller extention.
Example :
1 <apex:page standardController="Account"
2 extensions="ExtOne,ExtTwo" showHeader="false">
3 <apex:outputText value="{!foo}" />
4 </apex:page>
if ExtOne and ExtTwo, both have the method getFoo() then the method of ExtOne will be
executed.
A controller extension is any Apex class that contains a constructor that takes a single argument
of type ApexPages.StandardController or CustomControllerName, where
CustomControllerName is the name of a custom controller that you want to extend.
1 System.runAs(u) {
2 // The following code runs as user 'u'
3 System.debug('Current User: ' + UserInfo.getUserName());
4 System.debug('Current Profile: ' + UserInfo.getProfileId()); }
5 // Run some code that checks record sharing
6}
19 | P a g e
SOSL SOQL
stands for "Salesforce object search language". stands for "Salesforce object query language".
Works on multiple object at a same time. Need to write different SOQL for different
object.
All fields are already text indexed. SOQL against same field will be slow.
20 | P a g e
SOSL SOQL
Cannot used in Triggers. Can only be used in Can be used in Apex class and Triggers.
Apex class and anonymous block.
1 Decimal d = 100/3;
2 Double ans = d.setScale(2) ;
62.In Profile settings, what is difference between “Modify All Data” and “Modify
All” ?
Ans:
Modify All Data : Create, edit, and delete all organization data, regardless of sharing settings.
Modify All : Give Read, Add, Delete permission to selected Object, Create permission is not
included in Modify All permission.
63. If i want record level access then what should i use from Salesforce security
model?
Ans: Manual Sharing
63. If i want Object level access then what should i use from Salesforce security
model?
Ans: Profile
64. In OWD (Organization wide sharing), can i change the setting “Grant Access
Using Hierarchies” for Standard Objects ?
Ans: You cannot change it for Standard Objects However for Custom Objects its possible.
68. While setting OWD (Organization wide sharing), can we change/modify the
setting of child record in case of Master-Detail relationship?
Ans: No, Child record is controlled by the Parents setting.
70. 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?
Ans:
Lets 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”.
71. 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?
Ans : Yes. In profile, there is setting for “Transfer Record”•.
22 | P a g e
73. How to hide the “App Setup” Menu from user’s setup page?
Ans : In Profile, remove access “View Setup and Configuration”•.
74. While creating new profile for user, which existing profile should be copied?
Ans: If the new user is not System administrator then copy from “Standard User”• profile.
75. Who can run reports?
Ans : Users with permission “Run Report”• and access to report folder can only run the report.
76. What is Difference between “printable View” and “Export Details” button on
report?
Ans:
Printable View: formatting, grouping and subtotals are persisted.
Export Details: formatting, grouping and subtotals are lost.
79. Which permission is required to set the running user other than you in
dashboard?
Ans: “View All Data”• in profile.
80. Who can access “drag and drop dashboard”•?
Ans : User with permission “manage dashboard”•.
87. How to show loading image while Ajax call in Visualforce? OR how to show
image in <apex:actionStatus> tag in Visualforce?
Ans:
Salesforce Analytic Snapshot – Field Mapping between Source Report and Target Object
Customizations Supports custom fields Any - includes custom fields, objects, tabs,
configurations
Security Secured data access and over-the-air Secured data access and over-the-air managemen
management
Price Free for all editions of Salesforce Free for Unlimited Edition customers; available i
Professional Edition and Enterprise Edition for a
fee
Campaign members are created from lead, contact, or person account records. Salesforce
provides a variety of ways in which you can manage your campaign members. You can add and
update up to 50,000 campaign members at a time through lead, contact, and person account
reports; you can search for and add or edit multiple leads and contacts from the Manage
Members page; you can add an unlimited number of leads and contacts using a CSV import file;
or you can add members to a campaign one at a time from contact or lead detail pages.
Read More:
http://login.salesforce.com/help/doc/en/campaigns_managemembers.htm
http://login.salesforce.com/help/doc/en/campaigns_members_using.htm#topic-title
1 <apex:outputText
2 escape="false"
value="{!'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'}"/>
4 <html>
5 <head>
6 <title>test</title>
7 </head>
8 <body>test</body>
9 </html>
10 </apex:page>
Read more in detail in thread – http://boards.developerforce.com/t5/Visualforce-
Development/Changing-doctype-of-a-Visualforce-Page/td-p/82397/page/2
92. Onchange event does not work with <apex:actionsupport> in IE9. How to
resolve this error?
Ans: If we hide 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 Headre by using “showHeader=true” in Apex page.
93. If IE9 is not working with your custom visualforce page then how to tell your
visualforce code to run in IE8 compatibility mode?
Ans:
Add following metatag to pages:
94. It may happen that above tips will not work as lots of time the page header
already sent. then how to achieve same result using Apex?
Ans:
Add below line of code in Apex (Constructor)
1 Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
Read more tips and tricks to solve IE9 issue in Salesforce here.
28 | P a g e
95. How to display the formatted number / date in Visualforce ? Which component
should be used?
Ans : Use component “<apex:outputText>”.
Example : Format the number into currency.
96. You want to display the Encrypted field on Visualforce and you are using
component apex:outputText. Will it work for Encrypted fields?
Ans : 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.
COUNT()
COUNT(fieldName)
99. How to write the “Where” clause in SOQL when GroupBy is used for aggregate
functions?
Ans : We cannot use the “Where” clause with GroupBy for aggregate functions like SUM()
instead we will need 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
1 AND Name like '%ABC%'
Read more about Having clause
100. Lets 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?
Ans :
On load event, write the javascript code to autofocus any other field or any other non-visible
component.
Example .
1 <span id="focusDistraction"></span>
2 <script type="text/javascript">
/* prevent autopup of the date inputfield by the default focus
3
behavoir */
30 | P a g e
4 window.onload=function() {
5 document.getElementById('focusDistraction').focus();
6 }
7 </script>
101. How to force lead assignment rule via Apex while updating or adding the
Lead?
Ans : To enforce Assignment Rules in Apex you will need to perform following steps:
Example:
Example:
We cannot reference the enum directly since the enum itself is not visible to the page and you
can’t make it a property.
32 | P a g e
Example:
Apex class:
Resolution:
Add below method in Apex Controller:
104. How to generate the random string or random password using Apex?
Ans:
Example 1:
Access the Account name from Contact.
1 {!myContact['Account'][fieldname]}
Example 2:
6
LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus
7
WHERE IsConverted=true LIMIT 1];
8 lc.setConvertedStatus(convertStatus.MasterLabel);
9
10 Database.LeadConvertResult lcr = Database.convertLead(lc);
11 System.assert(lcr.isSuccess());
108. How can you determine that email is actually sent or not from the salesforce?
Ans:
There is an Email log that you could use. It’s available in the setup menu under Monitoring.
It’s only for the past 30 days and you would have to manually check it.
From the email log page: “Email logs describe all emails sent through salesforce.com and can be
used to help identify the status of an email delivery. Email logs are CSV files that provide
information such as the email address of each email sender and its recipient, the date and time
each email was sent, and any error code associated with each email. Logs are only available for
the past 30 days.”
110 : Give any scenario when you cannot change the currency field type to numeric
type.
Ans : When the field is used either in Apex class or trigger.
Map<String,Schema.RecordTypeInfo> RecordTypeInfo =
4
cfrSchema.getRecordTypeInfosByName();
5 Id rtId = RecordTypeInfo.get('Record Type Name').getRecordTypeId();
or
Schema.SObjectType.Object_API_Name__c.getRecordTypeInfosByName().get(
1
'recordtype name').getRecordTypeId()
112 : 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.
Ans:
1 List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();
2 Map<String,String> objectMap = new Map<String,String>();
3 for(Schema.SObjectType f : gd)
4{
objectMap.put(f.getDescribe().getKeyPrefix(),
5
f.getDescribe().getName());
6}
7
8 String sampleId ='00390000003LIVw';
9 String prefix = sampleId.substring(0,3);
10 String objectName = objectMap.get(prefix);
11 System.debug('** SObject Name ** '+objectName);
12
Map<String, Schema.SObjectField> desResult =
1
Schema.getGlobalDescribe().get(objectName).getDescribe().Fields.getM
3
ap();
1
List<String> fieldList = new List<String>();
4
15 fieldList.addAll(desResult.keySet());
16 for(integer i =0;i<fieldList.size();i++)
17 {
18 System.debug('** Field Name ** '+fieldList[i]);
19 }
36 | P a g e
113. Consider a scenario where you have created a Visualforce page and Controller.
You want to restrict the controller action for users which are logged in using
“Grant Login Access”. How to acheive this?
Ans:
When System admin logged in on the behalf of any other user. On upper right corner message is
displayed that user is logged-in on behalf of some other user. In Visualforce page we can search
for the element with class name present or not? If the element with that Class name exist means
logged-in user is not a actual user
114. How to get “https” link instead of “http” for Visualforce page using URLFOR()
in Email Template ?
Ans: 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
115. What is the best way to check whether organization have PersonAccount
enable or not using Apex?
Ans:
Method 1:
116 : When you get the error “Non-selective query against large object type”? how
to resolve it?
Ans : 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.
117 : How to get the debug log of Connection user in salesforce to salesforce
Integration?
Ans : When configuring Debug Logs, you cannot choose a Salesforce to Salesforce Connection
User from the User Lookup, but there is a workaround to
achieve this.
38 | P a g e
To begin capturing Debug Logs for a Connection User open the following URL in your browser:
https://XXX.salesforce.com/p/setup/layout/AddApexDebugLogUser?retURL=%2Fsetup%2Fu
i%2FlistApexTraces.apexp&UserLookupInput_lkid=YYYYYYYYYYYYYY
&UserLookupInput=Connection%20User
Replace XXX with your salesforce instance, UserLookupInput_lkid is the ID of the Connection
User and UserLookupInput is the User name. You can find
the user ID of the connection user, by inspecting the CreatedById for a record created by this
user. (eg. via eclipse or Force.com explorer)
Courtesy : http://screenfields.nl/blog/2012/08/09/debugging-salesforce-2-salesforce/
118 : 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?
Ans : In Constructor of the Controller extension, only Id of Custom Object is supplied. We need
to query all the required field explicitly in order to use in remaining part of the code.
119: Using Apex how you can determine that user is in Sandbox or production?
Ans : read this URL for answer
121 : Consider we have overall 90% code coverage however there is one class which
have 0% code coverage. Can we still able to deploy that class on production?
39 | P a g e
Ans : Yes. Minimum 1% required for every trigger and there is no such restriction for Apex
class.
122 : How to get selected records ID from List View using Javascript / Ajax Toolkit,
when custom button is added on List View page?
Ans : Create a new Button on Lead of type List Button. Add the button on Lead List View
Layout and write below Javascript code:
1 {!RequireScript("/js/functions.js")}
2
3 var recordsSelected = {!GetRecordIds($ObjectType.Lead)}
4 for(var i=0; i < recordsSelected .length ; i++) {
5 alert('Selected ID '+recordsSelected[i]);
6}
123 : 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?
Ans: 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!
125 : Lets consider you had created outbound changeset previously. After that,
some class is modified which is part of that old changeset. Can you reuse same
changeset to deployed changed component ?
Ans : Once changeset is created it cannot be modified. After creation of changset, if we modify
any component it will not reflected and we need to clone the changeset to reflect changes. More
information available here.
40 | P a g e
131. What will happen if you try to update record in After Trigger Context?
Ans : You will get an error saying “record is Read only”.
132. Let’s say we have to update the same record in After Trigger context. Is there
any way or workaround?
Ans : If we create a new instance of an 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.
5 {
6 Contact mirrorContact = mirrorResultMap.get(origContact.Id);
//origContact.Linked_Contact__c = mirrorContact.Id; //Link
7
the Original Record tot he Mirror Record WILL FAIL
133 . When loading data into date fields such as Opportunity Close Date using the
Data Loader, the date displayed in the application is sometimes one day earlier
than the date in the file. What may be the reason and solution ?
Ans :
The reason for this is that fields such as Close Date are actually date/time fields. When a date is
loaded without specifying the time, the time is defaulted to 00:00 – midnight. When another
user is in a time zone which is behind the current user’s time zone, the date will show on the
previous day. For example:
Similar issues can arise when daylight savings time begins or ends.
135 : 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 ?
Ans : While providing URL, do not specify the protocol. Use like this:
42 | P a g e
apex:ActionPoller : This is timer component which can send AJAX request on pre-defined
interval. Minimum interval is 5 sec and default is 60 sec.
137 : In how many ways you can invoke Controllers / Controller Extensions
method from VF?
Ans : Javascript Remoting, ActionFunction, ActionSupport, ActionPoller.
140 : User have all the permissions to see the Dashboard and Source Folder still
when he wants to see dashboard, its not visible. What might be the cause?
Ans : It is possible that Salesforce User license for Dashbaord running user is different than
User wants to access Dashboard. Example – Running User license is “Salesforce” and user
trying to access Dashboard is “Salesforce Plateform”.
141 : User Wants to set the starting day in Calendar as “Monday” instead of
“Sunday”. How to get it done?
Ans : Change the user locale to “English ( United Kingdom ) ” in Personal information or User
record.
145 : System admin has created a Visualforce for Account. In future he created few
more new Fields. How could System admin can code Visualforce so that in future if
any new field is added or existing field deleted. It should reflect in Visualforce
without changing anycode?
Ans : It can be done with help of Field Sets. Please read this article.
146 : Once you convert lead, Few fields on lead should be reset so that sensitive
information should not be queried using SOQL. How to get this done?
Ans : Once lead is converted, its READ ONLY. we cannot update it using Apex or Trigger.
However we can use “Before Update” trigger on lead and check for fiels “IsConverted“. If its
true means lead is going to be converted so reset all fields in that case.
148 : How to handle comma within field while uploading using DataLoader ?
Ans : Data Loader cannot handle this implicitly because there is no logical path to follow. In
case your Data Loader CSV file for import will contain commas for any of the field content, you
will have to enclose the contents within double quotation marks ” “. Data Loader will be able to
handle this.
For example :
1 Column_1__c,Column_2__c,Column_3__c
2 Shiva,"Jitendra, Minal",Soft
If you are creating the import CSV in Excel, the quotation marks will be inserted automatically
by Excel whenever a comma is detected in any cell – Saving the CSV in Excel and opening the
same in Notepad reveals the enclosing quotation marks for cells containing commas.
45 | P a g e
While creating record for detail object he selects parent record which is not
created by him. What will happen in this case ?
Ans : He will get an error, because in order to add child record user must have edit permission
in parent master record.
Export All : It is used to export the Salesforce Data(including recycle bin’s data) into your
local system.
151. Give Sample Code Snippet of Apex that that will show that how Parent and
Child record can be inserted in Single Statement ?
Ans : It can be done with help of External Id.
1 Date dt = Date.today().addDays(7);
Opportunity newOpportunity = new Opportunity(Name = 'shivasoft',
2
StageName = 'Prospecting', CloseDate = dt);
3
4 /*
Create the parent reference. Used only for foreign key reference and
5 doesn't contain any other fields. If we provide any other value it
will give following error
6
System.DmlException: Insert failed. First exception on row 1; first
7 error: INVALID_FIELD, More than 1 field provided in an external
foreign key reference in entity: Account: []
8 */
9
10 Account accountReference = new Account(MyExtID__c = 'SHIVA1234567');
11 newOpportunity.Account = accountReference;
12
13 // Create the Account object to insert. Same as above but has Name
46 | P a g e
152 . Which SOQL statement can be used to get all records even from recycle bin or
Achieved Activities?
Ans : We will need “ALL Rows” clause of SOQL.
Sample :
153. How can you lock record using SOQL so that it cannot be modified by other
user.
Ans : we will need “FOR UPDATE” clause of SOQL.
Sample :
154. If you set more than one savepoint, then roll back to a savepoint that is not the
last savepoint you generated, What will happen to later savepoint variables ?
Ans : if you generated savepoint SP1 first, savepoint SP2 after that, and then you rolled back to
SP1, the variable SP2 would no longer be valid. You will receive a runtime error if you try to use
it.
• Each savepoint you set counts against the governor limit for DML statements.
• Static variables are not reverted during a rollback. If you try to run the trigger again, the static
variables retain the values from the first run.
• Each rollback counts against the governor limit for DML statements. You will receive a Runtime
error if you try to rollback the database additional times.
• The ID on an sObject inserted after setting a savepoint is not cleared after a rollback.
47 | P a g e
• upsert triggers fire both before and after insert or before and after update triggers as
appropriate.
• merge triggers fire both before and after delete triggers for the losing records and before
update triggers for the winning record only.
• Triggers that execute after a record has been undeleted only work with specific objects.
• Field history is not recorded until the end of a trigger. If you query field history in a trigger, you
will not see any history for the current transaction.
• You can only use the webService keyword in a trigger when it is in a method defined as
asynchronous; that is, when the method is defined with the @future keyword.
• A trigger invoked by an insert, delete, or update of a recurring event or recurring
task results in a runtime error when the trigger is called in bulk from the Force.com API.
• Merge trigger doesn’t fire there own trigger instead they fire delete and update of loosing and
winning records respectively.
157. How to execute Apex from Custom button or Javascript ? Give Example.
Ans :
1 {!REQUIRESCRIPT("/soap/ajax/33.0/connection.js")}
2 {!REQUIRESCRIPT("/soap/ajax/33.0/apex.js")}
3 var account = sforce.sObject("Account");
4 var id = sforce.apex.execute("myClass" , "makeContact",
5 {lastName:"Smith", a:account});
To call a webService method with no parameters, use {} as the third parameter
for sforce.apex.execute .
48 | P a g e
Also, you can use the following line to display a popup window with debugging information:
sforce.debug.trace=true;
• Public class can be accessed within application or namespace. This is not exactly like public
modifier in Java.
• Global class visible everywhere , any application or namespace. WebService must be declared as
Global and which can be accessed inside Javascript also. It is like public modifier in Java.
Ans :
Ans :
161 : Sometimes while deleting record it gives error “Object cannot be Deleted”.
What is the reason for this kind of error ?
Ans :
This is generic error message prompted by Salesforce many times, which is not well informative.
To get informative message, we can try to delete same record in “Developer Console”. In
Developer Console Debug log, we will get exact error message.
Example : Lets say there is one record which is parent of more than 2000 records and grand
parent of 5000 records. In such scenario from developer console it gives error something
like “record cannot be deleted because it has many associated objects” However in User
Interface, it will just display that “Object cannot be deleted.“
“The move to separate domains has one very specific purpose: leverage the browser security
model (same domain policy) to protect our customers and the salesforce.com service from cross
site scripting and cross site request forgery attacks.
Moving to the serving pages from separate domains is a critical component of our ongoing
commitment to insure the highest level of security and availability for everyone.
In the world where everything is served from the same domain any custom page that you visit
had full access to any other page in your org and also any page served from salesforce.com itself.
This included potentially malicious code that was installed as part of a force.com package.”
163 : In below code snippet , What is your observation and what is going wrong ?
165. While creating Dynamic SOQL, which involves Datetime gives ” no viable
alternative at character ‘<EOF>’ ” error.
OR
value of filter criterion for field ‘CreatedDate’ must be of type dateTime and should
not be enclosed in quotes
OR
How to use Datetime in Dynamic SOQL Query in Salesforce ?
Ans :
This error is because of wrong construction of Dynamic Query with Datetime. following code
snippet will give idea on how to construct dynamic query for Datetime ?
166. How you can use Datetime field as a criteria in SOQL Query ?
Ans :
We cannot use Datetime as condition in Where Clause in between single Quotes.
You can do something like this ,
For more information on date formats and more literal values, check this URL.
167. After Data Export using DataLoader, Some time it appears that data is on New
Line (Carriage Return) when we open CSV file in Microsoft Excel. For example ,
Address Data separated on different lines. How can we override this problem ?
Ans :
Excel does all sorts of “useful” things when it opens a CSV file. It will re-format dates, strip
leading zeros, corrupt record IDs (if you have them in your report), and as explained it will also
break line. Best way as per my experience till date is, Upload document to Google Drive.
Export document back from Google drive as Excel.
Please post comment in this article if you know any other working way.
168. How do you import Converted Lead into Salesforce from Legacy System ?
Ans :
Fields we need for importing converted leads are “ISCONVERTED” ,
“CONVERTEDCONTACTID” , “CONVERTEDOPPORTUNITYID” and
“CONVERTEDACCOUNTID“.
Step 1 : As above fields are not editable, we have to contact Salesforce Support to enable Audit
fields. Enabling Audit fields means we can edit few Readonly fields like created date and above
lead fields.
52 | P a g e
Step 2 : Import Account, Contact and Opportunity from Legacy system to Salesforce.
Step 3 : If you imported account, contact and opportunity in Step 2, Salesforce automatically
generates Unique ID. We need that unique Id to insert Converted Lead. So Export Account,
Contact and Opportunity, which is inserted in Step 2 from legacy System.
Step 4 : Create CSV File with All lead information with ISCONVERTED=TRUE and
CONVERTEDCONTACTID, CONVERTEDOPPORTUNITYID, CONVERTEDACCOUNTID.
CONVERTEDCONTACTID, CONVERTEDOPPORTUNITYID and
CONVERTEDACCOUNTID should correspond to Ids generated by Salesforce for Contact,
Opportunity and Account which will be related to converted lead.
Step 5 : Once CSV is properly created with all required Data, Insert it using DataLoader.
Note : We cannot convert existing lead using this process. Leads must be inserted with these
four fields. If you try to update lead it will not give you option to edit above fields.
169. How to setup Field Level Security (FLS) for Person Account Fields.
OR
Why I am not able to find list of Person Account fields in Field Level Security (FLS)
settings when navigated to fields on Account Object.
Ans :
Field Level Security (FLS) of Person Account fields ar controlled by Contact Fields. So, if you
want to setup FLS of Person Account Fields navigate to fields of Contact and it will be reflected
on Person Account.
170. In Partner Community, external user is having appropriate OWD and Profile
Settings for Opportunity or consider any other Object. However they are getting
insufficient privilege access, what might be cause of this error ?
Ans :
• Check External User has all FLS for fields used in Report Filters
• After Winter 14, If Community enabled, there will be two kind of OWD. External and Internal
means what information should be visible to internal and external users. Also , there will be new
setting named “Standard Report Visibility“. If it is checked user can see reports based on
Standard report type even though they don’t have proper OWD and may expose sensitive
information about internal user to external users (for example : Internal users role). If external
user is getting an error whole running the report this setting may be one of the cause.
53 | P a g e
171 : How Standard Fields and Custom Fields related information is saved inside
Salesforce Database? Is every Standard and Custom Object is created as a different
Database table?
Ans :
Salesforce is using Multi-tenant architecture, means many organizations (Tenants) are using
same infrastructure. Salesforce Database saves Metadata Information in hundreds of table. Run
time engine then generates organization specific query to get information about their
organizations and Data from common table as shown in below diagram. Below Database tables
are partitioned by Organization ID and generates virtual table specific to Org.
172 : As a Developer, how can you optimize SQL query to fetch data from
Salesforce Database?
Ans :
As Salesforce doesn’t save data in traditional way. Data of all tenants are in common table, so
traditional Query optimization query and technique will not work in this case, so there is no
such tool available to optimize final generated SQL. We only have option to create SOQL which
is optimized by custom inbuilt Force.com Query Optimizer.
In Summer14, Salesforce released Query Plan Tool to analyze how query is performing. With
help of this tool, we can get an idea how we can change our query to perform better.
54 | P a g e
173 : When records are created in Salesforce, How it is queued for Indexing?
Ans :
If newly created records are equal to or less than 9000, then it will be indexed in 1 to 3 minutes.
However if records are more than 9000, then servers perform bulk indexing at a lower priority,
so processing might take longer.
1. Determines the best index from which to drive the query, if possible, based on filters in the
query
2. Determines the best table to drive the query from if no good index is available
3. Determines how to order the remaining tables to minimize cost
4. Injects custom foreign key value tables as needed to create efficient join paths
5. Influences the execution plan for the remaining joins, including sharing joins, to minimize
database input/output (I/O)
6. Updates statistics
Skinny Table
• RecordTypeId
• Division
• CreatedDate
• Systemmodstamp (LastModifiedDate)
• Name
• Email (for contacts and leads)
• Foreign key relationships (lookups and master-detail)
• The unique Salesforce record ID, which is the primary key for each object
56 | P a g e
• multi-select picklists
• text area (long)
• text area (rich)
• non-deterministic formula fields (Like any formula field using function NOW() or Today() )
• encrypted text fields
There are few standard fields also which are considered as non-deterministic which can be
found in salesforce documentations.
Two-column indexes are subject to the same restrictions as single-column indexes, with one
exception. Two-column indexes can have nulls in the second column by default, whereas single-
column indexes cannot, unless salesforce.com Customer Support has explicitly enabled the
option to include nulls.
186 : In case of parallel data loading, how to avoid record locked error ?
Ans : Record locked error can be avoided by two ways
1. Change schema of Object : Check every Lookup field and make sure that in Lookup Option
you have notselected “Don’t allow deletion of the lookup record that’s part of lookup
relationship”. Because of this selection, even during insert operation system hold lock against
record and other batches accessing same record fails.
2. Order Insert operations in CSV File : In this option, Sort column containing parent record
Id for Lookup fields. So all records of same parent will be loaded in same batch and parent
record locked problem across batch will be resolved. Check this Webinar recording for loading
20 millions record in one hour.
3. Other reasons of lock may be Rollup Summary, Workflow, Trigger etc.
58 | P a g e
181. Lets consider your custom Object named “Training__c” has field
“Trainer__c”. You have set some default value in that field. Will that default value
apply to new record created by apex code ?
OR
How to make sure that record created from apex code should respect default value
of fields ?
OR
Default value in field from Apex code.
Ans :
After API 20, it should automatically populate However there is known issue for same here, click
here if it impacts you.
Workaround :
If Default value of field is not getting populated by Apex then we have to use “Dynamic Apex”.
Create instance of object from sObjectType like shown below:
182. What is best practice to refer dynamic custom messages in Visualforce with
multi-language support ?
Ans :
Using Custom Label or OutputField or InputField tag, Platform itself will take care of
internationalization. However in some cases, Message needs to be dynamic at the same time it
should also support muti-language. In Custom Label, we cannot save dynamic String.
Let’s assume we want to show message something like “DEVELOPERNAME is not authorized to
access this page”.
Here, Developername should be dynamically changed in visualforce which
supports multilanguage. For each developername, it is not feasible to create custom labels. So
below workaround can be used :
59 | P a g e
Step 1 : Create a Custom Label with text “{0} is not authorized to access this page“. In every
language, dynamic value should represented by {0}.
183. How can you update Salesforce record using Apex, when you don’t know
Object API name, but you know record Id ?
Ans :
Using Dynamic Apex we can achieve this :
187. How we can check API limits already used in any organization by using REST
or SOAP API ?
Ans :
SOAP API and REST API always returns header after making successful call to Salesforce.
Sample Responses:
SOAP :
1 <soapenv:Header>
2 <LimitInfoHeader>
3 <limitInfo>
4 <current>45</current>
5 <limit>5000</limit>
6 <type>API REQUESTS</type>
7 </limitInfo>
8 </LimitInfoHeader>
9 </soapenv:Header>
REST :
1 Sforce-Limit-Info: api-usage=45/5000
188. Lets say you have written trigger on Opportynity and want to access field of
Account. Can you use this Syntax – oppObj.Account.someField__c ?
Ans : There is common missunderstanding that what is allowed in Trigger Context. Above
Syntax will work on any other places like Visualforce Controller. However in Trigger, Lookup
field or related list is not available implicitly, we need to query it.
61 | P a g e
189. How we can control Chatter email settings while creating or updating users
using Data Loader?
Ans : Using a dataloader update the user object’s field “DefaultGroupNotificationFrequency”
with the options:
190. Once email is sent via Workflow, can it be tracked in Activity history related
list ?
Ans : No. If you think this is nice to have and usefull for Auditing purpose, please vote up and
comment on this idea.
193. Currently, can you show Lightning components tab in Mobile as well in
desktop ?
Ans : Currently you can only use Lightning Components in the Salesforce1 Mobile App or a
standalone app.
62 | P a g e
• Lightning Component Framework – Components and extensions that allow you to build
reusable components, customize the Salesforce1 Mobile App, and build standalone apps.
• Lightning App Builder – A new UI tool that lets you build apps lightning fast, using components
provided by Salesforce and platform developers.
• Lightning Connect – An integration tool that makes it easier for your Force.com app to consume
data from any external source that conforms to the OData spec.
• Lightning Process Builder – A UI tool for visualizing and creating automated business
processes.
• Lightning Schema Builder – A UI tool for viewing and creating objects, fields, and relationships.
1 <apex:stylesheet value="{!URLFOR($Resource.style_resources,
'styles.css')}"/>
• Relative path in CSS from static resource, You can use relative paths in files in static
resource archives to refer to other content within the archive.
1 <apex:image url="{!URLFOR($Resource.TestZip,
64 | P a g e
1 {!$Component.Parent1.Parent2.fieldId}
• read more in this post.
• While updating class on Sandboxes, chances are high that it is being used in any
scheduler, so below code will abort all scheduled job. If there are 150+ scheduled job,
then you might want to use below code again and again in developer console until all
jobs are removed from system.
209. How to use standard Salesforce REST API from Visualforce page ?
Befor any Ajax call, make sure to add ‘Bearer’ token in header. If using JQuery use below code
snippet. For more information read this post.
1 $.ajax({
2 type: reqType,
3 beforeSend: function (xhr)
4 {
xhr.setRequestHeader("Authorization", 'Bearer
5
{!$API.Session_ID}');
6
7 },
211 : While creating JavaScript button to execute anonymous apex, what should
you keep in mind ?
Ans : End user must needs to have “Apex Author” permission and this is something should not
be granted to end user. Also, while creating JavaScript button, user must be aware that its only
supported in Salesforce classic and not in Salesforce Lightning.
213 : What may be reason truncate button is not visible on Custom Object ?
Ans :
• Are referenced by another object through a lookup field or that are on the master side of a
master-detail relationship
• Are referenced in a reporting snapshot
• Have a custom index or an external ID
• Chatter API is REST API for Chatter to display Salesforce data, especially in mobile applications.
Responses are localized, structured for presentation, and can be filtered to contain only what the
app needs.
• Connect API provides apex classes for accessing the same data available in Chatter REST API.
Use Chatter in Apex to create custom Chatter experiences in Salesforce.
217 : How to capture errors after using Database DML methods in Salesforce?
Ans :
SQL_Server_Id__c='3',firstName='Jitendra');
3 lstContact.add(con);
4 //.. Other Contact records added in List
Database.UpsertResult[] results = Database.upsert( lstSGAccOppInsert,
5
Contact.SQL_Server_Id__c.getDescribe().getSObjectField() ,false ) ;
6
7 for(Integer i=0;i<results.size();i++){
8 if (!results.get(i).isSuccess()){
9 Database.Error err = results.get(i).getErrors().get(0);
System.debug('Error - '+err.getMessage()
10 + '\nStatus Code : '+err.getStatusCode()+'\n
Fields : '+err.getFields());
11 }
12 }
When we create Geolocation field in Salesforce, lets say by name “location__c” then internally
Salesforce creates subfields with extension “__s“. In this case “location_latitude__s” and
“location_longitude__s”.
69 | P a g e
223 : How to redirect Salesforce flow after completion, if end URL is known in
advance?
Ans :
There are two approach :
1 https://instance.salesforce.com/flow/flowName?retURL=page_name
and second, if flow is used in Visualforce page then
1 <apex:page>
224 : What are difference between lookup and fast lookup data elements in flow?
Ans : Lookup record will return only first matching record however to get all matching record,
we should use fast lookup. Any data element with prefix “fast” means to work in bulk. As shown
in below image we have two flavors of Data element in flow for CRUD operation.
229 : How to set finish location of Salesforce Flow for newly created record inside
flow ?
Ans : Currently there is no way to set finish location of Salesforce flow by point and click or
Visualforce. We have to write Apex controller or controller extension to achieve this. Below is
sample code.
Visualforce code:
Apex code :
6 public Flow_redirect_finish(ApexPages.StandardController
stdController){
73 | P a g e
7 objAcc = (Account)stdController.getRecord();
8 }
9
10 private String readFlowVariable() {
11 if (contactFlow == null) return '';
12 else return contactFlow.varContactId;
13 }
14
15 public PageReference getNewRecordId(){
16 return new PageReference('/' + readFlowVariable() );
17 }
18 }
233. Can we select Person Account as parent for Business Account and create
Account hierarchy ?
Ans: Person Account is used for B2C & Business Account is B2B model in Salesforce. In real
life, headquarter or head office of business Account can never be person Account. Therefore we
cannot choose Person Account as parent Account for Business Account. It will throw error –
Parent Account may not be a person account.
74 | P a g e
234. Can we select Business Account as parent for Person Account and create
Account hierarchy ?
Ans: No. Standard Field Parent Account would not even appear on Person Account page
layouts if we try to add it.
235. Can you link Person Account to Person Account using standard Parent
Account field available on Account ?
Ans: No. Standard Field Parent Account would not even appear on Person Account page
layouts if we try to add it.
235. How to link Person Account with Parent Person Account or Business Account
?
Ans: Create a custom lookup field on contact of type Account. this field can be used to choose
parent Business Account or Person Account. We can also choose Contacts to Multiple
Accounts to relate Person Account and Business Account without creating custom field.
• At least one record type should exist for Account (Business Account)
• Org Wide Defaults (OWD) for Contacts should be Controlled by Parent
• Every profile which have read permission on Account should have read permission on Contact
as well.
75 | P a g e
Ans : If Company field on Lead contains value, then Business Account is created otherwise
Person Account.
240. As Person Account acts as Contact and Account. Which trigger would be
executed for Person Account ?
Ans : Account Trigger. Because under the hood, its Account which can be used as Contact.
Bonus Question 1 : How to traverse Person Account relational field from Account
in SOQL.
Ans : Let’s say, you have a lookup field created on Contact. This field would be available for
Person Account and can be referred using extension __pc. To traverse parent record in SOQL,
we replace __c by __r. In same way, we can traverse Person Account relational field
using __pr.