1. What is Force.com and Salesfore.com? Mention the differences.
Force.com is a cloud computing platform where the developers build multitenant applications.
Salesforce.com is also a cloud computing platform, it contains only standard objects.
Salesforce.com is hoisted on Force.com.They're effectively the same thing, but Salesforce.com
is generally used to refer to the CRM functionality (the sales, service and marketing
applications) and Force.com is generally used to refer to the underlying platform (the database,
code, and UI on which all the apps are built).Force.com is a platform where you can develop
your own application. Salesforce.com is Sales(CRM) and Service applications which were
developed and running on the Force.com Platform. The developed applications will run
on the force.com always as a multitenent architecture method. Simply you can identify
Forc.com is where you can access and customize your datamodel, bussiness logic and
UserInterface. But in case of salesforce.com you can access the sales(CRM) Application with all
the developed data model, Business logic and UserInterface. Then you can customize your
application funtionality, since it is running on the force.com platform. The difference b/w
salesforce & force.com is the salesforce is software as a service and the force.com is the
application development platform.the force.com is the platform as a service.
2.What are the Force.com editions and salesfoce.com editions?
Force.com includes 5 editions.
Free edition
Enterprise with one app
Enterprise with multiple app
Unlimited with one app
Unlimited with multiple apps
SalesForce.com includes 5 editions
Contact Manager
Group
Professional edition
Enterprise edition
Unlimited edition
3.How many custom objects available in Professional and Enterprise edition and
Unlimited?
Professional 50
Enterprises 200
Unlimited 2000
4.In Which edition the Apex Data Loader will support? What are those editions?
Earlier Enterprise and Unlimited editions use to support Apex data loader. Now, Professional,
Enterprise and Unlimited edition supports data loader.
5.Through Salesforce Import wizard how many records we can import into S.F Objects
and the wizard will support for which Objects?
Using Import wizard, we can upload up to 50000 records. And only Accounts, Contacts and
custom object’s data can be imported. If we want to import other objects like Opportunities and
other object’s data, then we need to go for Apex Data Loader.
6.In which edition work flows are available in S.F?
In Enterprise edition and in unlimited edition, we have these work flows. We do not have these
work flows in group and professional editions. We can get these workflows in professional
edition also as an add-on.
7.What is the data and file storage capacity in Professional and Enterprise and Unlimited
editions Org wide? What is the storage capacity for each user in above editions?
Data storage (Org) File storage (Org) Dstorage/Fstorage(User)
Professional 1GB 1GB 20MB/100MB
Enterprises 1GB 1GB 20MB/100MB
Unlimited 1GB 1GB 120MB/100MB
8.In Which Edition Outlook and Excel and Mobile Lite are available in S.F?
Mobile Lite users can view, create, edit, and delete accounts, assets, contacts, leads,
opportunities, events, tasks, cases, and solutions from mobile.
Mobile lite is available in all editions i.e.; Group edition, Professional edition, Enterprise edition,
Unlimited edition.
Outlook connect to sales force is used to sync contacts, Events and mails to sales force. Like
mobile lite feature this is also available in all above mentioned editions.
9.What is app exchange?
The developed custom applications can be uploaded into the app exchange so that the other
person can share the applicaition.
10. What is a VLOOKUP in S.F?
VLOOKUP is actually a function in sales force which is used to bring relevant value to that
record from another record automatically.
11. What are the types of bindings available in Visual force?
Using get; set in apex, we can bind variables in visual force.
ex: public String textdemo{get;set;} // in apex
<apex:input text value=”{!textdemo}”>
Using methods in controller
Ex: <apex:selectlist value=”textdemo”>
<apex:selectoptions value=”listt”/>
</apex:selectoptions>
//In apex
Public List<Account> getlistt(){
Return [select Id,Name from Account]; \\ returns list
}
12.What are the types of relationships present in S.F?
4 types
Master-Detail
Lookup
Junction Object
Hierarchy
13.What is junction Object and what does it mean?
Junction object is a custom object which is used to create many to many relationship between
two objects.
It always contains two Master-Detail relationships.
14.Differences between Master-Detail and Lookup
Both are used to create one to many relationship between two objects.
In case of MD, if Parent is deleted, child is also deleted.
In case of Lookup, if Parent is deleted, child is not deleted.
In MD, Child is mandatory, but in Lookup, child is not mandatory.
15.When I want to export data into SF from Apex Data Loader, which Option should be
enable in Profile?
Enable API
16. Types of Reports in S.F?
3 types of reports in S.F
Tabular reports: Tabular report is used to represent the data simply in tabular format.
Summarizing on a particular field cannot be done.
Summary reports: In summary report, we can summate or group the data based on a column.
Matrix report: In matrix report we can summarize the data both in rows and columns.
17.What is an Assignments rule?
It is a Rule to specify how leads are assigned to users or queues as they are created manually,
captured from the web, or imported via the lead import wizards.
18.What is a web- lead?
Capturing a lead from a website and routing it into lead object in Sales Force is called wed-lead
(web to lead).
19.What is lookup and Master Details and what is difference between them.
Both Lookup and Master detail fields are used to link a record in one object to another record in
another object.
In lookup, if we delete master records, child records will not be deleted.
In master-detail, if we delete master records, child records will also be deleted.
Child record is mandatory for Master-Detail.
20.What is an External Id?
External Id is an id that can be given to any field in an object. An external id will be generated on
the field that we mention. This field will be used to detect duplicate values when we try to import
data into sales force using an external system like apex data loader, informatica data loader etc.
21.What are the Types of Account and difference between them?
We have two types of accounts.
Personal accounts
Business accounts.
In personal accounts, person’s name will be taken as primary considerations where as in
business accounts, there will be no person name, but company name will be taken into
consideration.
22.How many ways to do a field is mandatory?
There are two ways to declare a field to be mandatory.
At the time of creating the field, mentioning the field should contain a value to save a record.
In page layout, we can mention the field to be mandatory.
23.What is a Field level Security?
Giving permissions to users based on Profiles.
Mentioning the availibity of a field to the users for viewing and editing purpose based on profile
is called field level security.
While creating a field,we can mention the security level of that field fr every profile by deciding
its level of accessibility to each profile.
24.Difference between Formula and Roll-up summary
Formula: is a read only field that derives a value from a formula expression that we define.
Roll-up summary: A read-only field that displays the sum, minimum, or maximum value of a field
in a related list or the record count of all records listed in a related list.
25.Difference btw isNull and isBlank
IsNull – it supports for Number field.
IsBlank- it supports for Text field.
26.What is a workflow? Types of workflow and actions in workflow.
Workflow is a force platform business logic engine that allows us to automatically send email
alerts, assign tasks, field updates based on rules that we define.
2 types:
Immediate actions: That executes when a record matches the criteria.
Time-dependent: When a record matches the criteria, and executes according to time triggers.
Actions:
Task : Assign a new task to user.
Email-alerts : Send email to one or more recipients that are specified.
Field Updates : Update value of a field.
Outbound Messages: Send a configurable API message to designed listener.
Types of email templates
Text
Html with letterhead
Custom Template
Visualforce.
27.Difference between Profiles and Roles
Profiles: Field level or Object level security can be given by profiles
Roles: Record level security can be given by Roles.
Profile is mandatory.
Types in roles:
Manual Sharing
OWD (organization wide default):
Public read
Public read/write
Private
Sharing rules
Role Hierarchy
28.What is a wrapper class?
A wrapper class is a class whose instances are collections of other objects.
29.What are collections and types of collections?
Collection is an object which groups multiple elements into a single unit.
List: Ordered collection of elements which allows duplicates.
Set: Unordered collection of elements which do not allow duplicates.
Map: Pair of two elements, in which the first element is always unique.
30.Types of Reports:
Tabular: Display data in a tabular form. No summarizing is allowed.
Summary: Summarize data on one column based on single criteria.
Matrix: Summarize data on both row and columns.
31.Difference between VF and S-Control
VF S-Control
It is a markup language like XML, HTML It is a procedural language like Java, Ajax
Automation of data is there- Binding No automation of data- Manual Binding
Style sheet(CSS) is included CSS is not included
Native
31. Accessibility of object
{! ($Objecttype.ObjectName.accessable)}----------- returns true if object is accessible.
32.What are Global keywords?
Used to access various values from components on a page or from user objects or from URL,
for each object we have each key word.
URL Current Page
Profile Page Reference
User Object Type
Resource Component
33.What is a Page Reference?
Page reference is a class in apex, which is used to redirect to another page.
By creating an object to this class, we can use this object to forward to another page as shown
in example below:
Public Pagereference go()
{
Pagereference p = new pageReference(‘http://www.google.com’);
Return p;
}
34.What is MVC?
The main aim of the MVC architecture is to separate the business logic and application data
from the presentation data to the user.
Model: The model object knows about all the data that need to be displayed.
View: The view represents the presentation of the application (User Interface).
Controller: Actual business logic of VF is present here.
35.What are the Controllers available in Force.com?
3 types of controllers are available
Standard Controller: Used for both custom and standard objects.
Custom Controller: is an apex class that implements all the logic for a page without leveraging
the functionality of a standard controller.
Extension Controller: is an apex class which adds functionality to existing standard and custom
controllers.
36.What is a difference between render, rerender and renderAs?
Render: is an attribute used in VF to hide or show certain components in visual force page.
Rerender: Used to refresh a part of a page in visual force page when an action occurs.
Render as: Used to convert entire visual force into PDF
Render as = “pdf”.
37.How can you access URL Parameters in to a visual force page?
Using $CurrentPage, you can access the query string parameters for the page by specifying
the parameters attribute, after which you can access each individual parameter.
$CurrentPage.parameters.parameter_name
Ex: $CurrentPage.parameters.location
38. What are annotations ant their types?
Annotations are used to bypass the methods in the way they execute.
@Future: Used to execute the methods asynchronously.
@IsTest: Used to test the methods.
@ReadOnly
@Deprecated
@Remote Action
39. What is a difference between <apex: dataTable />, <apex: pageBlockTable />?
Only standard style sheets used in page block table,
If we want to add custom style sheets we have to data table.
39.What is a Sandbox? Types of sandbox.
Sandbox is the exact replica of the production.
3 Types:
Configuration
Developer
Full
40.What are triggers? Types of Triggers
Trigger is a piece of code that is executed before or after a particular field of certain type is
inserted, updated or deleted.
Bulk Trigger: All triggers are bulk triggers by default, and can process multiple records at a
time. You should always plan on processing more than one record at a time.
Bulk triggers can handle both single record updates and bulk operations like:
Data import
Mass actions, such as record owner changes and deletes
Recursive Apex methods and triggers that invoke bulk DML statements.
Recursive trigger:
41.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.
42.ActionFunction: A component that provides support for invoking controller action methods
directly from JavaScript code using an AJAX request.
43.ActionPoller: A timer that sends an AJAX update request to the server according to a time
interval that you specify.
44.What is Batch Apex? How can you implement Batch Apex?(Dynamic Apex)
Batch Apex gives you the ability to operate over large amounts of data by chunking the job into
smaller parts, thereby keeping within the governor limits.
Using batch Apex, you can build complex, long-running processes on the Force.com platform.
For example, you could build an archiving solution that runs on a nightly basis, looking for
records past a certain date and adding them to an archive.
45.What is a Callout method? How does it invoke, how many methods available in
Classes and Triggers?
It is used to invoke the External services HTTP or web services.
An Apex callout enables you to integrate your Apex with an external service by making a call to
an external Web service or sending a HTTP request from an Apex script and then receiving the
response. Apex provides integration with Web services that utilize SOAP and WSDL, or HTTP
services (RESTful services).
46.What is a difference between System log and debug log?
System Log console is a separate window that displays debugging information, as well as its
cumulative limits and source code. It can be considered a context-sensitive execution viewer
showing the source of an operation, what triggered that operation, and what occurred afterward.
Use the System Log console to view debug logs that include database events, Apex processing,
workflow, and validation logic.
47.Debug log records database operations, system processes, and errors that occur
when executing a transaction or while running unit tests. The system generates a debug
log for a user every time that user executes a transaction that is included in the filter criteria.
48.SOQL : Salesforce.com Object Query Language
49.SOSL : Salesforce.com Object Search Language
50.What is a Force.com IDE?
Ans. Force.com IDE is a development environment which is available as a plug-in to be installed
in Eclipse and used. This IDE can be used to work on and manipulate the salesforce structure
like authoring Apex classes, Visual force pages, apex triggers etc.,
51.What is a Managed Package and Unmanaged package?
Managed packages are AppExchange packages that can be upgraded in the installer's
organization. They differ from unmanaged packages in that some components are locked,
allowing the upgrade process. Unmanaged packages do not include locked components and
can not be upgraded.
Before the Winter '07 release, all packages were unmanaged. Now, you can convert an
unmanaged package to managed to ensure your installed users get upgrades.
Unmanaged Package Managed Package
What Completely Editable by Developer and Installer
Can NOT be upgraded Certain Components are locked
No Destructive Changes to app
Supports Seamless Upgrading
Supports LMA for Managing Installs
When to Use 1:1 Distribution
Extensive Modification Required 1:Many Distribution
Commerical Intent
Foresee Upgrades
Editions Supported All Editions can create Unmanaged Packages ONLY Developer
Edition can create Managed Packages
Managed packages differ from unmanaged packages in many other ways. Before creating
managed packages, here are a few things to consider:
You must use a Developer Edition organization to create and work with a managed package.
A Developer Edition organization can contain a single managed package and many unmanaged
packages.
You must register a Namespace Prefix - A Namespace Prefix is a series of characters prefixed
to your Custom Objects and Fields to prevent conflict when installed in another salesforce.com
org.
When you release a managed package, meaning it is uploaded with the Managed - Released
option selected, the properties of its components change to prevent developers and installers
from making harmful changes. For a list of each package component type and their properties,
see Properties of Managed Packages. If you do not want to offer upgrades to your package,
consider keeping it unmanaged.
If you plan to release your app as a Managed Package, please read out guide on Planning the
Release of Managed Packages
If you already have a Unmanaged Package and you'd like to convert it to Managed, please
review the following: Converting Unmanaged Packages to Managed
Now that you understand the difference and benefits of each type of package, let's see how
easy it is to make your Unmanaged package from above into a Managed Package.
Customer portal
With Salesforce CRM’s customer portal, your customers can log cases and get updates 24x7.
All via the intuitive user experience for which Salesforce CRM is famous. The result—higher
customer satisfaction at a lower cost.
Partner portal
Outsource your service management by allowing third-party service reps to manage customer
cases via the partner portal. Service partners can do everything they need to resolve customer
support issues: search the solution database, log cases, make case comments, and run reports.
52.What are the rules Criteria to create a work flow? How many ways to fire a work flows
and when should those available? What are the actions in work flow?
Ans. Criteria that cause salesforce.com to apply the workflow rule.
Immediate actions that execute when a record matches the criteria.
Time-dependent actions that salesforce.com queues when a record matches the criteria, and
executes according to time triggers.
In 2 ways,
1. Immediate action: when criteria matches record then workflow will be fired immediately.
2. Timedependent action: Fires according to time triggers.
Tasks - Assign a new task to a user, role, or record owner.
Email Alerts - Send an email to one or more recipients you specify.
Field Updates - Update the value of a field on a record.
Outbound Messages - Send a secure configurable API message (in XML format) to a
designated listener.
53. Types of Sandboxes and what are those and In Which editions those are available?
Ans. 3 types of Sandboxes available, those are Developer, Full and Configuration. In all
editions.
54. What is test coverage code % for the classes and triggers and what is the test method
syntax?
Ans. 75%.
55.Types of Triggers and what is a Bulk Trigger?
Ans. All triggers are bulk triggers by default, and can process multiple records at a time. You
should always plan on processing more than one record at a time.
Bulk triggers can handle both single record updates and bulk operations like:
Data import
Bulk Force.com API calls
Mass actions, such as record owner changes and deletes
Recursive Apex methods and triggers that invoke bulk DML statements.
56.What are the types of bindings available in Visual force?
Ans . 1. Using GET-SET in apex, we can bind variables in visual force.
2. Using methods in controller.
57. What is a Wrapper Class in S.F?
Ans. A wrapper class is a class whose instances are collections of other objects.
59. What are formula and Rollup Summary fields and Difference between them? When
should Rollup- Summary field enable?
Formula: A read-only field that derives its value from a formula expression that we define. The
formula field is updated when any of the source fields change.
Rollup Summary: A read-only field that displays the sum, minimum, or maximum value of a field
in a related list or the record count of all records listed in a related list.
Difference is below:
Formula fields calculate values using fields within single record, roll-up summary
fields calculate values from a set of related records.
When we give the master-detail relationship it get’s enable to the master object
========================================================================
=
1. Name three Governor Limits.
Total number of SOQL queries issued 1 (This limit
doesn’t apply to custom metadata types. In a single
Apex transaction, custom metadata records can have
unlimited SOQL queries.)
100(Sync) 200(Async)
Total number of records retrieved by SOQL queries 50,000
Total number of records retrieved by
Database.getQueryLocator
10,000
Total number of SOSL queries issued 20
Total number of records retrieved by a single SOSL
query
2,000
Total number of DML statements issued 2 150
Total number of records processed as a result of DML
statements, Approval.process, or
database.emptyRecycleBin
10,000
Total stack depth for any Apex invocation that
recursively fires triggers due to insert, update, or
delete statements 3
16
Total number of callouts (HTTP requests or Web
services calls) in a transaction
100
Maximum timeout for all callouts (HTTP requests or
Web services calls) in a transaction
120 seconds
Maximum number of methods with the future
annotation allowed per Apex invocation
50
Maximum number of Apex jobs added to the queue
with System.enqueueJob
50
Total number of sendEmail methods allowed 10
Total heap size 4 6 MB 12 MB
Maximum CPU time on the Salesforce servers 5 10,000
milliseconds
60,000
milliseconds
Maximum execution time for each Apex transaction 10 minutes
Maximum number of unique namespaces referenced 6 10
Maximum number of push notification method calls
allowed per Apex transaction
10
Maximum number of push notifications that can be
sent in each push notification method call
2,000
1. When do you use a before vs. after trigger?
95% of triggers are before triggers.they’re simpler to use.
If you need to make any changes to a record entering your after trigger, you have to do a DML
statement.
This isn’t necessary in a before trigger – changes to records entering your trigger always save!
The specific use case of an after trigger is when you need to associate any record to a record
being created in your trigger.
1. What’s the maximum batch size in a single trigger execution?
Default batch size is 200 ,However maximum batch size is 2000.
1. What are the differences between 15 and 18 digit record IDs?
15 digit Id number will have numeric digits range from (0-9), a Lowercase letter(a-z) or a
Uppercase letters(A-Z). 15 digit ID in salesforce.com is case sensitive. Example
100000000000ABC is different from 100000000000abc. When using external productive tools
like Microsoft Excel, MS Access and SQL Server external ID’s are not case sensitive and they
don’t recognize the difference between 100000000000ABC and 100000000000abc.
Salesforce.com has recognized this problem and Salesforce.com has established 18 digit
character insensitive ID. This 18 Digit ID is case insensitive which is formed by adding a suffix to
the 15 Character Id number.
1. Provide an example of when a Custom Setting would be used during development.
Custom Settings vs. Custom Objects
In some ways, Custom Settings look very much like Custom Objects. In fact, if you use a tool
like the Data Loader to view a list of objects in your org, you’ll see that Custom Settings are
listed together with Custom Objects, without any visible distinction between the two. However,
while both Custom Objects and Custom Settings allow you to define Custom Fields, there are
some important differences.
● Limited field types – Custom Settings support only Checkbox, Currency, Date,
Date/Time, Email, Number, Percent, Phone, Text, Text Area, and URL field types. Most
notably absent are Formula and Picklist, as well as field types that define relationships to
other objects, like Lookup and Master/Detail. You can’t create lookups from Custom
Objects to Custom Settings either.
● No validation rules – You can’t define validation rules on Custom Settings.
● No workflow or triggers – You can’t define workflow rules or triggers on a Custom
Setting. Any validation of data, update of related records, or other actions that you might
use workflow or a trigger to perform for a Custom Object have to be implemented
differently for a Custom Setting.
● No page layouts or record types – You can’t re-arrange fields on the page layout for
Custom Settings. Custom Settings aren’t really intended to be visible to every-day users.
If you need them to be, you can create Visualforce pages to allow users to view and
manipulate Custom Setting data.
So if Custom Settings are so limited, why use them?
Avoiding Governor Limits
Depending on how your Apex code interacts with Custom Settings, they can have zero impact
on certain governor limits. That’s right – you can retrieve all of the values in a Custom Setting
with absolutely no impact on the governor’s count of the number of queries you’ve performed or
the number of rows you’ve retrieved. This makes Custom Settings particularly useful for
reference data , like lists of Postal Code / State mappings.
First, you have to query the Custom Setting in a very specific way in order to take advantage of
this “no governor limit” feature . Specifically, you have to use the Custom Setting’s GET
methods, not SOQL , to query for data. Second, other governor limits, like those on heap size
and number of script statements, do still apply . Even with these caveats, though, Custom
Settings can provide a welcome relief from the limits on queries and rows .
Hierarchical Access to Data
There are two types of Custom Settings: List and Hierarchy. List-type Custom Settings are very
similar to Custom Objects, but Hierarchy-type Custom Settings are very different. Hierarchy
Custom Settings allow you to associate specific rows with specific Users or Profiles. For
example, you could define a Hierarchy Custom Setting that associates a different commission
rate with different sales reps, with separate rows for each sales rep’s User Id. Then you could
add a formula field to the Opportunity object, and reference the Custom setting with a formula
like: $Setup.CustomSettingName__c.CustomSettingFieldName__c. Whenever someone views
an Opportunity record, the formula will be evaluated, and Salesforce will find the Custom Setting
row for the currently-running User; if none is found, it will find the row for the current User’s
Profile (if one has been defined); and if none is found again, it will find an organization-wide
default value (if defined).
This ability to define hierarchical data is very powerful , as it allows you to define user-specific
customizations. A common use of Hierarchy Custom Settings is to define application-specific
defaults on a user-by-user basis. For example, imagine you’ve developed a Visualforce page
displays a list of Accounts, allows the user to select one, and then displays the Cases for that
Account. You could store each user’s most recently selected Account in a Hierarchy Custom
Setting, and then, the next time the user visits the Visualforce page, it could pre-select the
Account that the user selected the last time he was on the page. Adding to the point above
Custom Setting stores data in the cache and can be retrieved without repetitive queries with
zero effect on governor limit unlike custom objects which stores data in database and in which
governor limit is ensured.
Custom setting is mainly used for string some static datas which can be used very frequently in
the application as well as you can built-in hierarchical logic that lets you “personalize” settings
for specific profiles or users in the Hierarchy Custom Settings
1. When should you build solutions declaratively instead of with code?
Force.com started out as a declarative development platform in its early days and continues to
provide a rich set of declarative development features to this day, so let’s dig in and find out
what we can (and should) do with clicks instead of writing code.
1. Give an example of a standard object that’s also junction object.
OpportunityContactrole is the junction between Opportunity and Contact,
Quote is junction between Contract and Opportunity.
PriceBookEntry is a junction between Product2 and Pricebook2
1. Describe a use case when you’d control permissions through each of the following:
2. – Profiles
3. – Roles
4. – Permission Sets
5. – Sharing Rules
6. When should an org consider using Record Types ?
7. What are some use cases for using the Schema class?
getGlobalDescribe()
Returns a map of all sObject names (keys) to sObject tokens (values) for the standard and
custom objects defined in your organization.
describeDataCategoryGroups(sObjectNames)
Returns a list of the category groups associated with the specified objects.
describeSObjects(sObjectTypes)
Describes metadata (field list and object properties) for the specified sObject or array of
sObjects.
describeTabs()
Returns information about the standard and custom apps available to the running user.
GroupStructures(pairs)
Returns available category groups along with their data category structure for objects specified
in the request.
1. A trigger is running multiple times during a single save event in an org. How can this be
prevented?
2. Why is it necessary for most sales teams to use both Leads and Contacts?
3. What is the System.assert method and when is it commonly used?
4. What are the differences between SOQL and SOSL?
SOQL(Salesforce object Query Language)
1)Using SOQL we can Search only on one object at a time.
2)We can query on all fields of any datatype
3)We can use SOQL in Triggers and classes.
4)We can perform DML operation on query results.
SOSL(Salesforce object Search Language)
1)Using SOSL we can search on many objects at a time.
2)We can query only on fields whose data type is text,phone and Email.
3)We can use in calsses but not in Triggers.
4)We cannot perform DML operation on search result
5. Order the following events after a record is saved:
– Validation rules are run1
– Workflows are executed4
– “Before” triggers are executed2
– “After” triggers are executed3
6. What is Trigger.old and when do you normally use it?
Trigger.new : Returns a list of the new versions of the sObject records. 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 : Returns a list of the old versions of the sObject records. Note that this sObject list is
only available in update and delete triggers.
7. When should you use a lookup instead of a master-detail relationship?
8. What are the advantages of using Batch Apex instead of a trigger?
Trigger will invoke when you will do any DML on particular Object . Batch apex you can execute
either when you want or you can schedule with a schedule job which will execute with schedule
Time .
Incase you have more number of record you need to execute then you should use batch apex
which will divide your records into different chunks and execute .
A Batch class allows you to define a single job that can be broken up into manageable chunks
that will be processed separately.
One example is if you need to make a field update to every Account in your organization. If you
have 10,001 Account records in your org, this is impossible without some way of breaking it up.
So in the start() method, you define the query you're going to use in this batch context: 'select Id
from Account'. Then the execute() method runs, but only receives a relatively short list of
records (default 200). Within the execute(), everything runs in its own transactional context,
which means almost all of the governor limits only apply to that block. Thus each time execute()
is run, you are allowed 150 queries and 50,000 DML rows and so on. When that execute() is
complete, a new one is instantiated with the next group of 200 Accounts, with a brand new set
of governor limits. Finally the finish() method wraps up any loose ends as necessary, like
sending a status email.
So your batch that runs against 10,000 Accounts will actually be run in 50 separate execute()
transactions, each of which only has to deal with 200 Accounts. Governor limits still apply, but
only to each transaction, along with a separate set of limits for the batch as a whole.
Disadvantages of batch processing:
--> It runs asynchronously, which can make it hard to troubleshoot without some coded
debugging, logging, and persistent stateful reporting. It also means that it's queued to run, which
may cause delays in starting.
--> There's a limit of 5 batches in play at any time, which makes it tricky to start batches from
triggers unless you are checking limits.
-->If you need access within execute() to some large part of the full dataset being iterated, this is
not available. Each execution only has access to whatever is passed to it, although you can
persist class variables by implementing Database.stateful.
--> There is still a (fairly large) limit on total Heap size for the entire batch run, which means that
some very complex logic may run over, and need to be broken into separate batches.
Trigger :-
1) synchronously process
2) You can do 100 SOQL per cycle
3) Trigger process 200 in one context
Batch job:-
1) asynchronously process
2) 200 SOQL per cycle
3) Depend of batch job size.
9. What are the pros and cons when using a Workflow Rule Field Update vs. a Formula
Field?
10. What are the differences between a Map and a List?
11. Describe a use case for Static Resources.
12. Provide an example of when a Matrix report would be used. How about a Joined report?
13. A group of users must be prevented from updating a custom field. What’s the most
secure method of preventing this?
14. When would you use the @future annotation?
You can use the future annotation when making an asynchronous Web service callout to an
external service for example. Without the annotation, the Web service callout is made from the
same thread that is executing the Apex code, and no additional processing can occur until the
callout is complete (synchronous processing). So, if you made a callout, and it just takes a long
time to make the call, it won't hit a limit and hurt your other code
15. List three different tools that can be used when deploying code.
Force.com Migration Tool Overview, Force.com IDE, change set
===================================================================
1. When should an Extension be used instead of a Custom Controller?
2. What are the advantages of using External Id fields?
3. What are the uses of the <apex:actionFunction> tag?
4. What are the differences between static and non-static variables in Apex?
5. What are some best practices when writing test classes?
6. What does the View State represent in a Visualforce page?
7. What are three new features in the most recent Salesforce release?
8. Describe the benefits of the “One Trigger per Object” design pattern.
Reusability – with your logic in a class, you can now re-use it outside of triggers, for example in
a Visualforce page, test class, batch Apex, etc. No need to copy code!
Simplicity – every “trigger” gets reduced to just two lines of code in the master trigger. An
object oriented code base is more organized, predictable, and modular too!
Control your order of execution – in Apex, “the order of execution isn’t guaranteed for multiple
triggers on the same object.” This pattern gives you total order control.
Code in style! You’re going to look like an Apex master using this pattern whether or not you
take advantage of any of the benefits above. Plus, it’s a common interview question!
9. Write a SOQL query that counts the number of active Contacts for each Account in a set.
10. Declaratively create logic in your org that prevents two Opportunities from being created
on a single Account in a single day.
11. Declaratively create logic in your org that prevents closed Opportunities from being
updated by a non System Administrator profile.
12. Coding challenges
13. 1) Describe Singleton in a Real Life Example , like if you want to explain concept of
singleton pattern to your grandmother, who don't know the computer at all. what would
be your approach. 2) How would you design a Chat Session (gtalk) ? 3) write program to
calculate power(x,n) in log(n) time 4) Find intersection node of two linked lists. 5) write
program to calculate power(x,n) in log(n) time 6) Merge two sorted linked lists into one
without extra space. 7) Given an array, which contains integers in the range of 1 to n.
one number is missing from it and one number is repeated in array. for ex -- array is
{1,2,3,4,4,6,7,8,9} , range given is 1- n(n=9). determine which number is missing and
which is repeated in array. 8) given char array = {a,a,a,a,b,b,b,c,c,d,d,,e,,f,f} output
should be -- {a,4,b,3,c,2,d,2,e,f,2}, i.e. occurrences of every element followed by
character, without using other array.
========================================================================
===
Questions
1. How many users have you supported.
2. What are permission sets and how do they differ from profiles.
3. When will you use profile and permission sets together.
4. Difference between roles and profiles.
5. What are controllers.
6. What are extensions.
7. Difference between controllers and extensions.
8. What is a standard controller, custom controller. Difference between the two.
9. When you override a button by specifying a VF page, what is a necessary condition for the VF
page to be available.
Ans - The VF page should have a standard controller listed for that object. Else, the VF page
will not be available to override a button.
10. Minimum number of queries required to query for 2 level, 3 level relationships.
11. How will you avoid recursive triggers.
12. How to bulkify triggers.
13. Understand basic SOQL and Apex limits.
14. What is with sharing and without sharing class.
15. How can sharing be done using Apex.
16. Explain the trigger handler pattern.
17. List few components which cannot be deployed using force.com IDE or change sets.
18. What deployment methods have you used. List advantages and disadvantages of each.
19. How will you load data for a child object.
20. Difference between a look up and master-detail relationship.
21. Explain, the way you will query child from parent and parent from child
22. What are sharing rules, when do you used sharing rules.
23. Explain lead to opportunity conversion.
24. What are record types. Why are the record types used.
25. When is page layout assignment used.
26. Can 1 user be assigned multiple profiles, if yes how, if not, what is the work around.
27. How many types of salesforce licenses are there. What are the limits.
28. Which license will I use if users will only use 1 custom application.
29. How can I create developer, full sandbox.
30. In how many days can one refresh a full sandbox.
31. What is batch apex. Why do we use batch apex.
32. What is @future method.
33. What are test classes, what is the test coverage you need to move a code into production.
34. Can I directly change code in salesforce production org.
35. How do I log a case with salesforce.
36. How can I change owner for multiple cases at once (example - from Rob to John)
37. Difference between a workflow rule and approval process.
38. What is the order of execution of workflow rules, validation rules, triggers.
39. Explain Salesforce.com security implementation with respect to Profiles, Roles and
Hierarchy, Sharing rules, OWD(org wide default settings). Also, specify which is the most
restrictive security setting.
40. What are custom report types.
41. What are different types of reports you can create.
42. What is Trigger.old and Trigger.New
43. What is ApexPages.addMessage
44. How is a pdf generated using visual force page.
45. How can I redirect user to a page after processing is completed in the controller/extension.
46. What are custom settings.
47. What are Action Support, Action Function and Action Poller used for.
48. What is rerender attribute used for.
49. What is package.xml
50. How can one read parameter values through the URL in Apex.
========================================================================
==
Notes
1. A child of one master detail relationship cannot be the parent of another.
2. Directly we cannot create master details relationship if custom object contains existing
records.
3. Following are the steps to create to create master-detail relationship when records are
available in custom object : First create field with lookup relationship. And then associate
ook field with parent record for every record. Next change the data type of the field from
look up to Master detail.
4. What is difference between trigger and workflow?
Workflow
Workflow is automated process that fired an action based on Evaluation criteria and rule
criteria.
We can access a workflow across the object.
We cannot perform DML operation on workflow
We cannot query from database
Trigger
Trigger is a piece of code that executes before or after a record is inserted or updated.
We can access the trigger across the object and related to that objects
We can use 20 DML operations in one trigger.
We can use 20 SOQL’s from data base in one trigger.
1. A Wrapper class is a class whose instances are collection of other objects. It is used to
display different objects on a Visual Force page in same table.
2. What is Difference between SOQL and SOSL?
3. SOQL(Salesforce Object Query Language)
4. Using SOQL we can Search only on one object at a time.
5. We can query on all fields of any datatype
6. We can use SOQL in Triggers and classes.
7. We can perform DML operation on query results.
8. SOSL(Salesforce object Search Language)
9. Using SOSL we can search on many objects at a time.
10. We can query only on fields whose data type is text,phone and Email.
11. We can use in calsses but not in Triggers.
12. We cannot perform DML operation on search result
13. Using insert() we can insert the records but if any error occurs in any record system will
throw an error insertion fail and none of the records are inserted.
14. If we want to execute partially success of bulk insert operation we will use database
.insert()
15. The maximum size of Static Resources for an organization is 250mB.
16. We can use that static resource script file as follows in Visual Force page
17. <apex: includescript values=” {! $Resource.fileName}”/>
18. How many ways we can share a record?
19. Role Hierarchy:
20. If we add a user to a role, the user is above in the role hierarchy will have read access.
21. Setup -> manage users -> roles -> setup roles -> click on ‘add role’ -> provide name and
save.
22. OWD:
23. Defines the base line setting for the organization.
24. Defines the level of access to the user can see the other user’s record
25. OWD can be Private, Public Read Only, Public Read and Write.
26. Setup -> Security Controls -> sharing settings -> Click on ‘Edit’
27. Manual Sharing:
28. Manual Sharing is sharing a single record to single user or group of users.
29. We can see this button detail page of the record and this is visible only when OWD
setting is private.
30. Criteria Based Sharing rules:
31. If we want to share records based on condition like share records to group of users
32. Whose criteria are country is India.
33. Setup -> security controls -> sharing settings -> select the object and provide name and
34. Conditions and save
35. Apex sharing:
36. Share object is available for every object(For Account object share object is AccountShare
). If we want to share the records using apex we have to create a record to the share
object.
37. Role is Record level access and it is not mandatory for all users. Profile is object level and
field level access and it is mandatory for all users.
38. What is the maximum size of the PDF generated on visualforce attribute renderAs?
15MB
39. Salesforce come under SAAS so, we can use one controller and as many extension
controllers for a single vf page.
40. Action function: Invoke the controller method from java script using AJAX and we can
use action function from different places on visual force page.
41. Action support: Invoke the controller method using AJAX when even occurs on page like
onMouseOver, onClick, ect… and we can use action support for particular single apex
component.
42. How many ways we can call the Apex class?
43. 1. Visual force page
44. 2. Web Service
45. 3. Triggers
46. 4. Email services
47. Permission sets extend user’s functional access without changing user’s profile.A user
has only read access through profile on custom object, administrator want to give access
Edit and create operations to him without changing the profile. Administrator creates
the permission set having edit and creates operation on custom object and assign to that
user.
48. Manual sharing is to share a record to a particular user manually.
49. Go to detail page of record and click on manual sharing button and assign that record to
other user with Read or Read/Write access.
50. Manual Sharing button enables only when OWD is private to that object.
51. How we can change the Grant access using role hierarchy for standard objects?
52. Not possible.
53. If user have only Read access on particular record but he wants to change the owner
name of that record, then in profile level Transfer Record enables he can able to change
the owner.
54. Maximum we can use 10 field dependencies in VF page.
55. Record Types are restrict the pick list values and assign to the different page layouts for
different Record Types.
56. Audit Trail provides the information or track all the recent setup changes that an
administrator done to the organization. This can store the last 6 months data.
57. We can add up to 20 reports in single dashboard.
58. If you update or delete a record in its before trigger, or delete a record in its after trigger,
you will receive a runtime error.
59. upsert triggers fire both before and after insert or before and after update triggers as
appropriate.
60. merge triggers fire both before and after delete triggers for the losing records and before
update triggers for the winning record only. See Triggers and Merge Statements .
61. Triggers that execute after a record has been undeleted only work with specific objects.
See Triggers and Recovered Records .
62. 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.
63. Field history tracking honors the permissions of the current user. If the current user
doesn't have permission to directly edit an object or field, but they activate a trigger that
changes an object or field with history tracking enabled, no history of the change is
recorded.
64. In API version 20.0 and earlier, if a Bulk API request causes a trigger to fire, each chunk
of 200 records for the trigger to process is split into chunks of 100 records. In Salesforce
API version 21.0 and later, no further splits of API chunks occur. If a Bulk API request
causes a trigger to fire multiple times for chunks of 200 records, governor limits are reset
between these trigger invocations for the same HTTP request.
65. The after undelete trigger event only fires for the following objects:
● Account
● Asset
● Campaign
● Case
● Contact
● ContentDocument
● Contract
● Custom objects
● Event
● Lead
● Opportunity
● Product
● Solution
● Task
1. order of execution
Executes all after triggers.
Executes assignment rules.
Executes auto-response rules.
Executes workflow rule
If the record was updated with workflow field updates, fires before update triggers and after
update triggers one more time (and only one more time), in addition to standard validations.
Custom validation rules and duplicate rules are not run again.
Executes escalation rules.
Executes entitlement rules.
updates the roll-up summary field in the parent record. Parent record goes through save
procedure.
If the parent record is updated, and a grandparent 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 grandparent record. Grandparent record goes through save procedure.
Executes Criteria Based Sharing evaluation.
Commits all DML operations to the database.
Executes post-commit logic, such as sending email.
=================================================
Links :
Link 1
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.
3. What is a Visualforce Page ?
Ans: 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
accomplished by using Visualforce Markup Language and the business logic can be
written in custom controllers associated with the Page.
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.
5. Where to write Visualforce code ?
Ans: 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,
https://ap1.salesforce.com/apex/MyTestPage. you 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 it self.
3. Using EclipseIDE you can create the Visulaforce page and write the code.
6.What are Apex Governor Limits?
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.
7. How to create and host S Control in Salesforce ?
http://JitendraZaa.com/blog/webtech/salesforce/how-to-create-s-control-in-salesforce/
h ttp://JitendraZaa.com/blog/webtech/salesforce/how-to-host-s-control-in-visualforce-pag
e/
8. Difference between Sandbox and Development environment?
http://JitendraZaa.com/blog/webtech/salesforce/difference-between-sandbox-and-develo
per-edition-in-salesforce/
9. How to schedule export or take the backup of salesforce?
http://JitendraZaa.com/blog/webtech/salesforce/backup-the-salesforce-data/
10. Do governor limits apply to sandbox instances?
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.
11. What is difference in ISNULL and ISBLANK?
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.
for further study you can read this link.
12. Is it possible to write the Apex code from user Interface?
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 sandbox organization. In a Salesforce.com production organization,
you can only make changes to Apex by using the Metadata API ,
deploycall, the Force.com IDE, or theForce.com Migration Tool. The Force.com IDE and
Force.com Migration Tool are free resources provided by salesforce.com to support its
users and partners, but are not considered part of our Services for purposes of the
salesforce.com Master Subscription Agreement.
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.
For more study, check this article
14. What are the types of email templates available in salesforce.com?
1. Text
2. HTML with Letter Head
3. Custom HTML
4. Visual force
To study more on email templates, refer this article
15. What are the different Salesforce.com Editions and Limits?
Ans : check this URL
16. What is Roll up summary field in Salesforce?
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
17. What will happen if the Account is deleted?
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:
Account Child relationship in salesforce
If we use schema builder, released in Winter 12 it would look like:
Account Contact and Opportunity of salesforce in schema builder
18. How many types of the relationship fields available in Salesforce?
Ans :
1. Master Detail
2. Many to Many
3. Lookup
4. Hierarchical (It is available only on User Object, we cannot create this
relationship)
For further study read this.
19. 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
autonumber as unique identification and create two master relationships for both
objects, no need create tab for this object.
Now on both object, add this field as related list.
Check this article on blog to create many to many relationship in detail.
To study more in detail, please refer salesforce documents.
20. In Which sequence Trigger and automation rules run in Salesforce.com 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. All Apex “before” triggers (EE / UE only)
5. Custom Validation Rules
6. Record saved to database (but not committed)
7. Record reloaded from database
8. All Apex “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)
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 : Salesforce.com 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 all logic in one trigger you may also be able to optimize on your
SOQL queries.
22. How to delete the User from Salesforce?
Ans : As per now, salesforce does not allow to delete any user, however you can
deactivate the user.
Read further…
23. How to delete the users data from Salesforce?
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 :
Returns a list of the new versions of the sObject records.
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 :
Returns a list of the old versions of the sObject records.
Note that this sObject list is only available in update and delete triggers.
26. How to restrict any Trigger to fire only once OR how we can avoid repeated
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.
1 public class HelperClass
{
2 public static boolean firstRun = true;
3 }
4 trigger affectedTrigger on Account (before delete, after delete, after undelete) {
5 if(Trigger.isBefore){
6 if(Trigger.isDelete){
7 if(HelperClass.firstRun){
8 Trigger.old[0].addError('Before Account Delete Error');
9 HelperClass.firstRun=false;
1
0
}
1
1
}
1
2
}
1
3
}
27. What is difference between WhoId and WhatId in the Data Model of Task ?
Ans :
WhoID refers to people things. So that would be typically a Lead ID or a Contact ID
WhatID refers to object type things. That would typically be an Account ID or an
Opportunity ID
Check Data Model of task here
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.
Following are the conditions to get the report of related objects:
● On both the objects, Reports option must be enable.
● Both object must be related either using Lookup or Master Detail type of
field.
Read this article, to get detailed idea on this topic.
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”.
30 : What is the dynamic Apex?
Ans :
Dynamic Apex enables developers to create more flexible applications by providing
them with the ability to “Access sObject and field describe information”, “Write
Dynamic SOQL Queries”, “Write Dynamic SOSL Queries” and “Dynamic DML”.
31 : How to get the list of all available sobject in salesforce database using Apex
(Dynamic Apex)?
Ans:
1 Map<String, Schema.SObjectType> m =
Schema.getGlobalDescribe();
32 : 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 will be decided at runtime, how
you will handle it? Hint : Use Dynamic Apex.
Ans:
1 public SObject
getNewSobject(String t)
2 {
3
4 // Call global describe to get the map of string to token.
5 Map<String, Schema.SObjectType> gd =
Schema.getGlobalDescribe();
6
7 // Get the token for the sobject based on the type.
8 Schema.SObjectType st =
gd.get(t);
9
1
0
// Instantiate the sobject from the token.
11 Sobject s = st.newSobject();
1
2
1
3
return s;
1
4
}
33 : How to get all the fields of sObject using dynamic Apex?
Ans:
1 Map<String, Schema.SObjectType> m =
Schema.getGlobalDescribe() ;
2 Schema.SObjectType s =
m.get('API_Name_Of_SObject') ;
3 Schema.DescribeSObjectResult r =
s.getDescribe() ;
4 Map<String,Schema.SObjectField> fields =
r.fields.getMap() ;
34 : How to get all the required fields of sObject dynamically?
Ans:
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 field 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
1 Map<String, Schema.SObjectType> m =
Schema.getGlobalDescribe() ;
2 Schema.SObjectType s =
m.get(so.apiName) ;
3 Schema.DescribeSObjectResult r =
s.getDescribe() ;
4 Map<String,Schema.SObjectField> fields =
r.fields.getMap() ;
5
6 for(String f : fields.keyset())
7 {
8 Schema.DescribeFieldResult desribeResult =
fields.get(f).getDescribe();
9 if( desribeResult.isCreateable() && !desribeResult.isNillable() &&
!desribeResult.isDefaultedOnCreate() )
1
0
{
11 //This is mandatory / required
field
1
2
}
1
3
}
35 : How to display error messages in the visualforce page ?
Ans:
In Apex use below code to create the error message for visualforce.
1 Apexpages.addMessage( new ApexPages.Message
(ApexPages.Severity.ERROR, 'Required fields are missing. '));
in Visualforce page add below tag where you want to display the error message.
<apex:pageMessages ></apex:pageMessages>
36 : What is property in Apex? Explain with advantages.
Ans:
Apex mainly consist 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 creates the setters and getters for that variable.
1 private String
name;
2 public void
setName(String n)
3 {
4 name =
n;
5 }
6 public String
getName()
7 {
8 return
name;
9 }
However, the Apex introduced the new concept of property from language C# as
shown below:
1 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.
37 : What is the controller extension ?
Ans:
Any apex class having a public constructor with Custom Controller or Standard
Controller object as a single argument is known as controller extension.
38 : Explain the need or importance of the controller extension.
Ans:
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.
39 : How to read the parameter value from the URL in Apex?
Ans:
Consider that the parameter name is “RecordType”.
1 String recordType =
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 of the Child records.
Look up relationship is something like “has-a” (Containership) relationship. Where one
record has reference to other records. When one record is deleted then there is no
impact on other records.
41. Can we convert the lookup relationship to Master Detail relationship?
Ans:
We can convert the lookup relationship to master detail relationship if and only if all the
existing record has valid lookup field.
42. In How many way we can invoke the Apex class?
Ans:
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.
45. What is the difference between database.insert and insert ?
Ans:
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 DML database methods (Database.insert) used, then if error occurs the
remaining records will be inserted / updated means partial DML operation
will be done.
46. What is the scope of static variable ?
Ans:
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.
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,
1 SO_Country__c code =
ISO_Country__c.getInstance("˜INDIA');
2 //To return a map of data sets defined for the custom object (all records in
the custom object), //you would use:
3 Map<String,ISO_Country__c> mapCodes =
ISO_Country__c.getAll();
4 // display the ISO code for
India
5 System.debug("˜ISO Code:
"˜+mapCodes.get("˜INDIA').ISO_Code__c);
6 //Alternatively you can return the map as a
list:
7 List<String> listCodes =
ISO_Country__c.getAll().values();
48. What happen if child have two master records and one is deleted?
Ans :
Child record will be deleted.
read more in this article.
49. What is Difference in render, rerender and renderas attributes of visualforce?
Ans:
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.
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
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 :
1 scheduledMerge m = new
scheduledMerge();
2 String sch = '20 30 8 10 2
?';
3 system.schedule('Merge Job', sch,
m);
To see how to make crone job string – R efer this Online Crone Expression Generator
tool .
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.
51. Explain Permission sets released in Winter 12.
Ans :
A permission set is a collection of settings and permissions that give users access to
various tools and functions. The settings and permissions in permission sets are also
found in profiles, but permission sets extend users’ functional access without changing
their profiles. For example, to give users access to a custom object, create a permission
set, enable the required permissions for the object, and assign the permission set to the
users. You never have to change profiles, or create a profile for a single use case. While
users can have only one profile, they can have multiple permission sets.
52. What is the difference between External ID and Unique ID?
Ans:
External ID
This is a field that usually references an ID from another (external) system. For instance,
if the customer has an Oracle Financials system that they will be linking with
salesforce.com, it may be easier for them to be able to refer to the Oracle ID of account
records from within salesforce. So they would create an external ID in salesforce.com
and they would load the Oracle ID into that field for each account. They can then refer to
that ID field, rather than the salesforce.com id.
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) .
External Id available for Text, Number and Email field types.
External Id is used in upsert operations.
● If external id is absenor not matched then insert happens.
● If external id matched once then record will be updated.
● If external id is matched multiple times then error occurs.
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.
Salesforce – External Id option while creating field
53. How to get the picklist value in Apex class?
Ans :
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>.
54. What are the types of controller in visual force?
Ans :
There are basically two types of Controller in Visual force page.
1. Standard Controller and
2. Custom Controller
55. How many Controllers can be used on single VF page?
Ans :
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.
56. Explain System.runAs()
Ans :
Generally, 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 all runAs() test methods
complete.
Example :
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 }
57. Explain Test.setPage().
Ans:
It is used to set the context to current page, normally used for testing the visual force
controller.
58. What is the custom settings ?
Ans :
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 Web services API.
59. Types of the custom settings?
Ans :
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. Examples
of list data include two-letter state abbreviations, international dialing prefixes, and
catalog numbers for products. 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.
60. Difference between SOSL and SOQL in Salesforce ?
Ans :
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.
Cannot used in Triggers. Can only be used in
Apex class and anonymous block.
Can be used in Apex class and
Triggers.
61. How to round the double to two decimal places in Apex?
Ans:
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.
65. What is Mandatory while creating User, Role or Profile?
Ans : Its Profile.
66. In case of Master-Detail relationship, on Update of master record can we update the
field of child record using workflow rule?
Ans: No
67. In case of Master-Detail relationship, on Update of child record can we update the
field of Parent record using workflow rule?
Ans: Yes, the Master fields are also available for “Criteria evaluation”.
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.
69. What is the need of “Custom Controller” in Visualforce as everything can be done by
the combination of Standard Controller + Extension class.
Ans :
● 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.
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” .
72. In Which Scenario share object “MyCustomObject__share” is not available/created
for custom object “MyCustomObject” ?
Ans: The object’s organization-wide default access level must not be set to the most
permissive access level. For custom objects, this is Public Read/Write. For more
information, see Access Levels . This object is used for creating Apex based sharing.
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.
Salesforce Report – Printable view and Export Details
77. What is the use of “floating report header” ?
Ans: If you have long tabular report, you can make the column header visible on each
pages as you scroll, by enabling floating report headers.
78. How to enable “floating report header” ?
Ans :
Go to “Setup | App Setup | Customize | Report and Dashboard | User Interface Settings “.
Click on checkbox “Enable Floating Report Headers” .
Salesforce Enable Floating Reports Headers
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” .
81. Which type of report can be used for dashboard components?
Ans : Summary and matric report.
82. How many types of dashboard components are available?
Ans : Chart, Table, Metric and Gauge.
83. Explain dynamic Dashboard.
Ans : Dashboard which is running under current logged in user permission are known as
“dynamic Dasboard” . At the most 3 dynamic dashboards can be built. Available in
Unlimited, Enterprise and developer edition. This type of dashboard cannot be scheduled
for refresh. IT must be scheduled manually.
84. What is the default timeout period while calling webservice from Apex.
Ans : 10 sec.
Read more at –
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_callouts_timeouts.
htm
85. A single Apex transaction can make how many callouts to an HTTP request or
an API call ?
Ans : Maximum 10 callouts
86. How to increase timeout while calling web service from Apex ?
Ans :
1 docSample.DocSamplePort stub = new
docSample.DocSamplePort();
2 stub.timeout_x = 2000; // timeout in
milliseconds
87. How to show loading image while Ajax call in Visualforce? OR how to show
image in <apex:actionStatus> tag in Visualforce?
Ans:
1 <div style="position:absolute;top:20px;left:
50%;">
2 <apex:actionStatus id="refreshContent"
>
3 <apex:facet name="start" >
4 <apex:image url="{!$Resource.LoadingImage}"
/>
5 </apex:facet>
6 </apex:actionStatus>
7 </div>
88. What is analytic Snapshot in salesforce?
Ans : Analytic snapshot capture and store the data at pre decided intervals. It
captures data from report and saves in custom object as per schedule. It only
supports tabular and summary report as a source report. It does not support
matrix report. The field type in target object must be same as source report object
field.
Salesforce Analytic Snapshot – Source Report and Target Object
Salesforce Analytic Snapshot – Field Mapping between Source Report and Target
Object
89. What is difference between Mobile Lite and Salesforce Mobile?
Ans :
Feature Mobile Lite Salesforce Mobile
Edit capabilities All standard objects Any app, any record
Customizations Supports custom fields Any - includes custom fields,
objects, tabs, configurations
Records Most recently used records;
search only
All records
Objects Leads, accounts, contacts,
opportunities, tasks, events,
cases, solutions, assets, and
dashboards
All objects
Custom objects None Any
Initial set of
records
Recently viewed on Web Fully configurable
Download
additional records
Using live search Using live search
Security Secured data access and
over-the-air management
Secured data access and
over-the-air management
Price Free for all editions of
Salesforce
Free for Unlimited Edition
customers; available in
Professional Edition and
Enterprise Edition for a fee
90. What is features of “Manage Members” in campaign records?
Ans :
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
91. How to add the Document Header in Visualforce page?
Ans : Directly there is no way to add the document type in visualforce. However in most
of the cases IE9 does not work with Visualforce pleasantly. And then we need to add the
Document type in header. So following workaround will work.
1 <apex:outputTe
xt
2 escape="fals
e"
3 value="{!'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
" 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
>
1
0
</apex:page
>
Read more in detail in thread –
http://boards.developerforce.com/t5/Visualforce-Development/Changing-doctype-of-a-Vis
ualforce-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.
Read more in detail in below thread URL :
http://boards.developerforce.com/t5/Apex-Code-Development/IE9-requires-header-in-VFPage/
td-p/402997
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:
1 <meta http-equiv="X-UA-Compatible"
content="IE=EmulateIE8" />
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.
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.
1 <apex:outputtext value="{0, number,
000,000.00}">
2 <apex:param
value="{!valFromController}" />
3 </apex:outputte
xt>
OR
1 <apex:outputtext value="{0, number,
###,###.00}">
2 <apex:param
value="{!valFromController}" />
3 </apex:outputte
xt>
Read in Detail , here
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.
Below Questions related to Group by clause in SOQL
97. Will below query work? Explain.
1 SELECT COUNT(Id), Name, Address__c FROM Opportunity
GROUP BY Name
Ans :
Above query will throw 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 will result in error “Malformed Query”.
Read more here in detail – Group by Documentation
98. Explain difference in COUNT() and COUNT(fieldname) in SOQL.
Ans :
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.
COUNT(fieldName)
● 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.
Read here in more detail about COUNT() and 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”.
1 SELECT COUNT(Id) , Name FROM Opportunity GROUP BY Name Having
COUNT(Id) > 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">
3 /* prevent autopup of the date inputfield by the default focus behavoir
*/
4
window.onload=function()
{
5
document.getElementById('focusDistraction').focu
s();
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:
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.
Example:
1 // to turn ON the Assignment Rules in
Apex
2 Database.DMLOptions dmlOptn = new
Database.DMLOptions();
3 dmlOptn.assignmentRuleHeader.useDefaultR
ule = true;
4 leadObj.setOptions(dmlO
ptn);
102. How to implement the pagination in SOQL ?
Ans:
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
Example:
1 Select Id, Name from Lead LIMIT 5
OFFSET 2
Above query will return 5 Lead records starting from record number 10 (5×2).
Read more here about SOQL pagination
103. Access custom controller-defined enum in custom component ?
Ans :
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:
1 global with sharing class
My_Controller {
2 public Case currCase {get; set;
}
3 public enum StatusValue {RED,
YELLOW, GREEN}
4
5 public StatusValues
getColorStatus() {
6 return StatusValue.RED; //demo code - just return
red
7 }
8 }
Visualforce page:
1 <apex:image url='stopsign.png' rendered="{!colorStatus ==
StatusValue.RED}" />
Above code snippet will throw error something like “Save Error: Unknown
property ‘My_Controller.statusValue'”
Resolution:
Add below method in Apex Controller:
1 public String currentStatusValue { get{ return
getColorStatus().name(); }}
and change Visualforce code to
1 <apex:image url='stopsign.png' rendered="{!currentStatusValue
== 'RED'}" />
The same question was raised in this thread of stackExchange
104. How to generate the random string or random password using Apex?
Ans:
1 Integer len =
10;
2 Blob blobKey =
crypto.generateAesKey(128);
3 String key =
EncodingUtil.convertToHex(blobKey);
4 String pwd =
key.substring(0,len);
105. What is dynamic binding in salesforce?
Ans:
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.
1 {!myContact['Account'][fieldn
ame]}
Example 2:
Consider Data type in Apex
1 public Map<String, List<Account>> accountsMap
{get; set;}
Visualforce page:
1 <apex:variable value="A"
var="selectedKey" />
2 <apex:pageBlockTable
value="{!accountsMap[selectedKey]}" var="acc">
3 <apex:column
value="{!acc.name}"/>
4 <apex:column
value="{!acc.BillingStreet}"/>
5 <apex:column
value="{!acc.BillingCity}"/>
6 <apex:column
value="{!acc.BillingPostalCode}"/>
7 </apex:pageBlockTa
ble>
Read more about Visualforce dynamic binding on bob buzzard’s blog
106. How to convert lead using Apex?
Ans:
1 Lead myLead = new Lead(LastName = 'Foo',
Company='Foo Bar');
2 insert
myLead;
3
4 Database.LeadConvert lc = new
database.LeadConvert();
5 lc.setLeadId(myLead.
id);
6
7 LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus
WHERE IsConverted=true LIMIT 1];
8 lc.setConvertedStatus(convertStatus.Master
Label);
9
1
0
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.”
109. In salesforce which fields are indexed automatically?
Ans :
The following fields are indexed by default:
● primary keys (Id, Name and Owner fields),
● foreign keys (lookup or master-detail relationship fields),
● audit dates (such as LastModifiedDate),
● Custom fields marked as External ID or Unique.
Read more on indexing from Salesforce Documentation
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.
111 : How to get the Recordtype Id using Dynamic Apex?
Ans:
Normally to get the RecordtypeId for any sObject we use SOQL and it will count
against your limit. So below method will bypass the need of SOQL Query.
1 Map<String, Schema.SObjectType> m =
Schema.getGlobalDescribe() ;
2 Schema.SObjectType s =
m.get('API_Name_Of_SObject') ;
3 Schema.DescribeSObjectResult cfrSchema =
s.getDescribe() ;
4 Map<String,Schema.RecordTypeInfo> RecordTypeInfo =
cfrSchema.getRecordTypeInfosByName();
5 Id rtId = RecordTypeInfo.get('Record Type
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 {
5 objectMap.put(f.getDescribe().getKeyPrefix(),
f.getDescribe().getName());
6 }
7
8 String sampleId
='00390000003LIVw';
9 String prefix =
sampleId.substring(0,3);
1
0
String objectName =
objectMap.get(prefix);
11 System.debug('** SObject Name **
'+objectName);
1
2
1
3
Map<String, Schema.SObjectField> desResult =
Schema.getGlobalDescribe().get(objectName).getDescribe().Fields.getMap
();
1
4
List<String> fieldList = new
List<String>();
15 fieldList.addAll(desResult.keySet
());
1
6
for(integer i
=0;i<fieldList.size();i++)
17 {
1
8
System.debug('** Field Name **
'+fieldList[i]);
1
9
}
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
1 <a href='{!URLFOR('/apex/SomePage', null,
[id=Some_Object__c.Id,retURL="/apex/SomeOtherPage"])}'>Go to
SomePage here!</a>
We can use something like :
1 <a href='{!SUBSTITUTE(URLFOR('/apex/SomePage', null,
[id=Some_Object__c.Id,retURL="/apex/SomeOtherPage"]),'http:','https:')}
'>Go to SomePage here!</a>
115. What is the best way to check whether organization have PersonAccount enable or
not using Apex?
Ans:
Method 1:
1 // Test to see if person accounts are enabled.
2 public Boolean
personAccountsEnabled()
3 {
4 try
5 {
6 // Try to use the isPersonAccount field.
7 sObject testObject = new Account();
8 testObject.get( 'isPersonAccount' );
9 // If we got here without an exception, return true.
1
0
return true;
1
1
}
1
2
catch( Exception ex )
1
3
{
1
4
// An exception was generated trying to access the isPersonAccount field
1
5
// so person accounts aren't enabled; return false.
1
6
return false;
1
7
}
1
8
}
Method 2:
1 // Check to see if person accounts are
enabled.
2 public Boolean
personAccountsEnabled()
3 {
4 // Describe the Account object to get a map of all fields
5 // then check to see if the map contains the field 'isPersonAccount'
6 return Schema.sObjectType.Account.fields.getMap().containsKey(
'isPersonAccount' );
7 }
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.
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%2
Fui%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
120: Can you use aggregate expressions inside inner query?
Explanation – Can you use Group by clause inside inner query in SOQL?
Example : Something like :
1 SELECT Id, Name,(SELECT Count(Id),Name FROM Contacts Group By
Name Having count(Id) > 1 ) FROM Account
Ans: 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“.
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?
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!
124 : In Custom Component How we can return value to Custom Controller or
Controller Extension?
Ans: In Apex, Objects are passed by reference ( read this article to understand Pass by
Value and Pass by reference in Salesforce and also read this Salesforce blog article ). 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.
125 : Lets 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?
Ans : 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 (offcource old copy of component) will be added to changeset.
126 : We have a “Time Based Workflow” and there is Action scheduled to be executed. If
we Deactivate the workflow, Scheduled actions will be removed from queue or not?
Ans : Even after deactivation of workflow, its action will be active in queue.
127 : We have “Time Based Workflow” and there is action scheduled to be executed. Can
we delete that workflow?
Ans : If a workflow have any pending time dependent action, then we cannot delete the
workflow.
128 : How to clear the Time based workflow action queue ?
Ans : Two ways to achieve this : 1. Make criteria false for all those records. 2. Navigate to
“Set up | Monitoring | Time Based Workflow”, search for scheduled actions and remove
from queue.
129 : While creating workflow on Task, what difference observed on available actions?
Ans : “Send Email” action is not available while creating workflow on task.
130 : In trigger, lets say we have system.debug() statement after adderror() method. Will
system.debug() be statement executed in Trigger after adderror() method?
Ans: adderror() method is not error statement rather its normal execution flow and all the
statements written after adderror() will be executed normally.
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.
1 List<Contact> originals = new
List<Contact>();
2 if(mirrorResultMap.values().size() > 0)
3 {
4 for(Contact origContact : contactRecs.values())
5 {
6 Contact mirrorContact = mirrorResultMap.get(origContact.Id);
7 //origContact.Linked_Contact__c = mirrorContact.Id; //Link the Original
Record tot he Mirror Record WILL FAIL
8 Contact origContactUpdate = new Contact(Id=origContact.Id,
Linked_Contact__c = mirrorContact.Id); //This will WORK
9 originals.add(origContactUpdate);
1
0
}
1
1
//update contactRecs.values(); //Update the Records -> THIS WILL FAIL AS ITS
ORIGINAL RECORDS IN MEMORY
1
2
update originals;
1
3
}
Credit goes to Cory Cowgill for this Blog Entry .
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:
20 August 2008 00:00 in Paris is 19 August 2008 23:00 in London
Similar issues can arise when daylight savings time begins or ends.
Two simple solutions to this are:
1) Specify a time as well as a date when loading dates using the Data Loader.
or
2) Switch your PC’s time zone to Hawaiian time before starting up the Data Loader.
134 : System.debug() statements are included against script count?
Ans : Any statement ending with semi-colon will be included against script count. There
is very good article by Abhinav explaining this here.
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:
1 <script type='text/javascript' src=
'//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js'></script>
136 : Explain ActionFunction, ActionSupport and ActionPoller in Visualforce.
Ans:
apex:ActionFunction : This component helps to envoke AJAX request (Call
Controllers method) directly from Javascript method. It must be child of
apex:form. Read here –
www.salesforce.com/us/developer/docs/pages/Content/pages_compref_actionFu
nction.htm
apex: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. Read more
here.
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.
138 : What is the use of apex:detail component ?
Ans : With the help of this Visualforce component, we can diretly get complete behavior
of page layout defined for logged in users profile. There is no need to add fields, related
lists explicitly. Read more here.
139 : What is the difference between “apex:dataTable” and “apex:pageBlockTable”
components in Visualforce?
Ans : Both component is used to render data in tabular format. dataTable will
render records in simple HTML table format whereas the “pageBlockTable”
possess default look and feel of salesforce standard CSS and must be written inside
“apex:pageBlock” componet.
You can read more here.
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.
142 : Why CSS is not working in PDF created by Visualforce ?
Ans : In Many cases, i have observed problems faced by my colleagues and
complaining that CSS is not working when they try to render any Visualforce page
as “PDF”. Same Question is asked many times in Interviews also. Basically there
are two ways:
1. Use “apex:stylesheet” tag to import external CSS file
2. Wrap “Style” tag inside “Head” tag in Visualforce
143 : How to get Ip Address of User in Apex?
Ans :
1 String ipAddress =
ApexPages.currentPage().getHeaders().get('X-Salesforce-SIP');
True-Client-IP has the value when the request is coming via the caching
integration.
X-Salesforce-SIP has the value if there is no caching integration (sandbox,
developer edition orgs) or via the secure url.
Thanks to TechNrd for this tips.
144 : How to get total number of Child records in Lookup relationship?
Ans: As Rollup Summary field is only supported in Master detail, we cannot use it
for Lookup. There are following two ways (If anyone has any other idea please
comment).
1. Inline Visualforce page
2. Trigger on Child Object, which will update field in Parent record if child record is
inserted, deleted or undeleted.
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.
147 : How to convert carriage returns in Textarea to Line Breaks in Visualforce?
Ans : We can use “<apex:outputField>” instead of “<apex:outputText>”. It will
maintain formatting automatically.
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,Colum
n_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.
149 : In Master Detail Relationship :
OWD for Parent is public Read Only.
If User has – Create, Edit Permission on Master as well as Detail Object.
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.
150 : Difference in “Export” and “Export All” in Data Loader in Salesforce?
Ans :
Export : It is used to export the Salesforce Data(excluding recycle bin’s data) into
your local system.
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);
2 Opportunity newOpportunity = new Opportunity(Name = 'shivasoft',
StageName = 'Prospecting', CloseDate = dt);
3
4 /*
5 Create the parent reference. Used only for foreign key reference and
doesn't contain any other fields. If we provide any other value it will give
following error
6
7 System.DmlException: Insert failed. First exception on row 1; first error:
INVALID_FIELD, More than 1 field provided in an external foreign key
reference in entity: Account: []
8 */
9
1
0
Account accountReference = new Account(MyExtID__c =
'SHIVA1234567');
11 newOpportunity.Account =
accountReference;
1
2
1
3
// Create the Account object to insert. Same as above but has Name field.
Used for the insert.
1
4
Account parentAccount = new Account(Name = 'Shiva', MyExtID__c =
'SHIVA1234567');
15
1
6
Database.SaveResu
lt[]
17 results = Database.insert(new SObject[] { parentAccount,
newOpportunity });
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 :
1 SELECT COUNT() FROM Contact WHERE AccountId
= a.Id ALL ROWS
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 :
1 Account [] accts = [SELECT Id FROM Account LIMIT 2
FOR UPDATE];
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.
155. What are few limitations (points to remember) of Savepoint or Transaction
Control in Apex ?
Ans :
● 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.
156. What are few Considerations about Trigger ?
Ans :
● 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 can you call Apex class using Javascript ? Give Example.
Ans :
1 global class
myClass {
2 webService static Id makeContact (String lastName,
Account a) {
3 Contact c = new Contact(LastName = lastName, AccountId =
a.Id);
4 return c.id;
5 }
6 }
we can execute above method from javascript like :
1 var account =
sforce.sObject("Account");
2 var id = sforce.apex.execute("myClass" ,
"makeContact",
3 {lastName:"Smith",
a:account});
To call a webService method with no parameters, use {} as the third parameter for
sforce.apex.execute .
Also, you can use the following line to display a popup window with debugging
information:
sforce.debug.trace=true;
158. What is difference between public and global class in Apex ?
Ans :
● 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.
159. Explain Considerations for Static keyword in Apex.
Ans :
● Apex classes cannot be static.
● Static allowed only in outer class.
● Static variables not transferred as a part of View State.
● Static variables and static block runs in order in which they are written in
class.
● Static variables are static only in scope of request.
160. Explain few considerations for @Future annotation in Apex.
Ans :
● Method must be static
● Cannot return anything ( Only Void )
● To test @future methods, you should use startTest and stopTest to make it
synchromouse inside Test class.
● Parameter to @future method can only be primitive or collection of
primitive data type.
● Cannot be used inside VF in Constructor, Set or Get methods.
● @future method cannot call other @future method.
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. “
162 : Why are Visualforce pages served from a different domain?
Ans :
If we see carefully, all our Visualforce pages are served like
“c.YOURSERVER.visual.force.com/apex/YOURPAGENAME” ,
And because of this most of time we run into Same-Origin Policy error in Javascripyt if
we try to access parent page from Iframe. Following reason is explained by one of the
evangelist of Salesforce:
“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 ?
1 trigger TestBeforeDelete on Lead (before Delete)
{
2
3 for(Lead l : Trigger.Old)
4 {
5 l.addError('error');
6 }
7
8 String msgBody = 'Test Email';
9 String Subject = 'Test from Cogni Force on Lead';
1
0
Messaging.SingleEmailMessage mail = new
Messaging.SingleEmailMessage();
1
1
String[] toAddresses = new String[] {'abc@gmail.com'};
1
2
mail.setToAddresses(toAddresses);
1
3
mail.setReplyTo('abc@gmail.com');
1
4
mail.setSenderDisplayName('Cogniforce Test Simulator');
1
5
mail.setSubject(Subject);
1
6
mail.setPlainTextBody(msgBody);
1
7
mail.setHTMLBody(msgBody);
1
8
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail
});
1
9
}
Ans :
It will not send any email. Because “adderror” prevents all transactions from committing
including emails.
164. Can we mass delete reports using Apex (Anonymous Apex) ?
Ans :
Salesforce has not exposed any API for Reports. So best way is :
1. Move all reports needs to delete in new folder.
2. Inform everyone that reports will be deleted after some time may be 30 days.
3. Import your reports folder in Eclipse including all reports to be deleted and then
delete the the reports folder in eclipse. It will delete all the reports at once.
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 ?
1 //format the datetime to make it Dynamic Soql
ready
2 String formatedDt =
cutOffDateTime.format('yyyy-MM-dd'T'HH:mm:ss'Z'');
3 String sql = 'SELECT a.Id FROM Agents_Answer__c a WHERE
a.Agents_Test_Result__r.Agent_Name__r.IsActive__c = false AND
LastModifiedDate < '+ formatedDt ;
Where, “cutOffDateTime” is variable of datetime type.
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 ,
WHERE CreatedDate > 2005-10-08T00:00:00Z
Or, you can also use Date Literals like
WHERE CreatedDate > YESTERDAY
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.
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.
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 Multitenant 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.
Salesforce Metadata Related Information in Database
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.
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.
174 : Explain functionality of Force.com Query Optimizer.
Ans :
The Force.com query optimizer:
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
175 : Explain term “Data Skew” in Salesforce.
Ans :
Scenario in which parent record has more than 10,000 of records or if any user owns
more than 10,000 records is known as “Data Skew” . Salesforce does not recommend
having more than 10,000 records own by any user or more than 10,000 Child for any
parent.
176 : Explain Skinny table.
Ans :
Salesforce creates skinny tables to contain frequently used fields and to avoid joins, and
it keeps the skinny tables in sync with their source tables when the source tables are
modified. To enable skinny tables, contact salesforce.com Customer Support.
For each object table, Salesforce maintains other, separate tables at the database level
for standard and custom fields. This separation ordinarily necessitates a join when a
query contains both kinds of fields. A skinny table contains both kinds of fields and does
not include soft-deleted records.
This table shows an Account view, a corresponding database table, and a skinny table
that would speed up Account queries.
Skinny Table
177 : What are the considerations for Skinny Table?
Ans :
● Skinny tables can contain a maximum of 100 columns.
● Skinny tables cannot contain fields from other objects.
● Skinny tables are not copied to sandbox organizations. To have production skinny
tables activated in a sandbox organization, contact salesforce.com Customer
Support.
178 : Which fields are automatically Indexed in Salesforce?
Ans :
● 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
179 : Which fields cannot be added as a custom Index?
Ans :
● 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
180 : When Salesforce will use Standard Indexed fields?
Ans :
Salesforce maintains statistics table which stores information about records present in
Organization. If records going to be searched is less than or equal to 30% of total records
or up to 1 million records then only it makes sense to use standard Indexed fields to
narrow result else total records going to be returned is more than 30% already so
Salesforce will not use any indexing.
181 : When Salesforce will use Custom Indexed fields?
Ans :
Salesforce maintains statistics table which stores information about records present in
Organization. If records going to be searched is less than or equal to 10% of total records
or up to 333,333 records then only it makes sense to use standard Indexed fields to
narrow result else total records going to be returned is more than 10% already so
Salesforce will not use any indexing.
182 : What are examples of Non-deterministic Force.com formula fields?
Ans :
● Reference other entities (i.e., fields accessible through lookup fields
● Include other formula fields that span over other entities
● Use dynamic date and time functions (e.g., TODAY and NOW)
● If formula field includes
○ Owner, autonumber, divisions, or audit fields (except for CreatedDate and
CreatedByID fields
○ References to fields that Force.com cannot index
○ Multi-select picklists
○ Currency fields in a multicurrency organization
○ Long text area fields
○ Binary fields (blob, file, or encrypted text)
There are few standard fields also which are considered as non-deterministic which can
be found in salesforce documentations .
183 : Explain Two-Column Custom Indexes.
Ans :
Two-column custom indexes are a specialized feature of the Salesforce platform. They
are useful for list views and other situations in which you want to use one field to select
the records to display and a second field to sort those records.
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.
184 : What is Defer Sharing Calculation ?
Ans :
This feature allows users to defer the processing of sharing rules until after new users,
rules, and other content have been loaded. This is very useful and handy feature to
speed up data loading by avoiding calculation of Sharing rules.
185 : How can we load millions of records in Salesforce within an hour ?
Ans : We can use Bulk Data loading and turn ON Parallel loading. Check this Webinar
recording for loading 20 millions record in one hour.
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 not selected “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.
Salesforce Bulk Data Load – Lookup fields
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:
1 Training__c tr= (Training__c) Training__c.sObjectType.newSObject(null,
true);
2
3 //Check if Value in field "Trainer__c" is default value
4 System.assertEquals('Jitendra', tr.Trainer__c);
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 :
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}.
Step 2 : In Controller of Visualforce write something like this :
1 String developerName = 'Some
DeveloperName';
2 String message = String.format(Label.DEVELOPERNA, new String[] {
developerName });
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 :
1 //Lets assume this is record Id
2 Id recId =
'a0P9000000ESXcV';
3
4 Schema.SObjectType token =
recId.getSObjectType();
5 Sobject s =
token.newSobject();
6 s.put('Id',recId );
7 s.put('Name', 'om');
8 update
s;
184. How to disable Header ribbon in Salesforce Organization where Community is
enabled ?
Ans : In Profile “View Global Header” controlls visibility of B lack ribbon whioch is used
to switch between community.
185. How many record can be displayed in repeater or PageBlockTable in Visualforce ?
Ans : current limit is 1000 records.
186. How to display more than 1000 records in repeater or PageBlockTable component of
Visualforce ?
Ans : If circumstances permits, we can use readOnly attribute available at apex page
level. Read more about making complete page readonly.
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:Heade
r>
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.
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:
● Email on each post
● Daily digests
● Weekly digests
● Never
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 .
191. Why do we still need Visualforce once Lightning will be GA ?
Ans : Visualforce provides the facility for delivering template-driven web pages and email
messages. In addition, developers wishing to simply utilize a basic container and
maintain more control over the lifecycle of the request may choose Visualforce pages.
Finally, organizations that can’t use Apex code can’t use Lightning Components, but they
can use Visualforce.
192. What is difference between Visualforce Components and Lightning Components ?
Ans : Visualforce provides the facility for delivering template-driven web pages and email
messages. In addition, developers wishing to simply utilize a basic container and
maintain more control over the lifecycle of the request may choose Visualforce pages.
Finally, organizations that can’t use Apex code can’t use Lightning Components, but they
can use Visualforce.
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.
194. What are Lightning Extensions?
Ans : They’re a mechanism for using custom-built components to replace existing
components in the Salesforce1 Mobile App. This functionality is currently in Pilot.
195. What is Aura?
Ans : Aura is the open source technology that powers Lightning Components. The aura:
namespace contains all of the basic building blocks for defining components and
applications.
196. Is it mandatory requirement to have namespace to create Lightning components ?
Ans : Currently yes, However Salesforce is planning to remove this dependency so that
default namespace can be used. As currently namespace is mandatory, we can crete
ligtening components only in developement organization but can be deployed on any
salesforce instance where Apex is enabled.
197. Where Lightning components can be displayed ?
Ans :
● In Lightning App (.app URL)
● In Salesforce1 app as a Tab
● As a lightning extension
198. How to include external javascript file in lightning component ?
Ans : You can use a RequireJS component or Loader component to load external JS or
CSS files.
199. Is it possible to use other frameworks like AngularJs or KendoUI with lightning
components ?
Ans : Yes
200. What are the tools included in lightning ?
Ans :
● 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.
201. Common Apex page attributes.
1 <apex:page sidebar="false" standardStylesheets="false"
showHeader="false">
202. Declare Visualforce page as HTML5.
1 <apex:page
docType="html-5.0" />
203. Visualforce page output as JSON .
1 <apex:page controller="ControllerName" contentType="application/x-JavaScript;
charset=utf-8" showHeader="false" standardStylesheets="false" sidebar="false">
2 {!jsonString}
3 </apex:page
>
204. How to refer static resources in Visualforce .
CSS File :
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 table { background-image: img/testimage.gif
}
Image tag:
1 <apex:image url="{!$Resource.TestImage}" width="50"
height="50"/>
or
1 <apex:image url="{!URLFOR($Resource.TestZip, 'images/Bluehills.jpg')}"
width="50" height="50"/>
Include Javascript in Visualforce from Static resource
1 <apex:image url="{!$Resource.TestImage}" width="50"
height="50"/>
Refer static resource path from Aprx Controller
1 global class MyController
{
2 public String getImageName() {
3 return 'Picture.gif';//this is the name of the image
4 }
5 }
1 <apex:page renderAs="pdf"
controller="MyController">
2 <apex:variable var="imageVar"
value="{!imageName}"/>
3 <apex:image url="{!URLFOR($Resource.myZipFile,
imageVar)}"/>
4 </apex:page
>
205. How to get element id of Visualforce components to be used in Javascript ?
1 {!$Component.Parent1.Parent2.fieldI
d}
read more in this post .
206. Autogenerated Salesforce Id consist of colon, how to handle it in JQuery ?
1 var ele = $('[id="abc:xyz"]');
read more about problem here .
207. How to return Map result from SOQL query in Apex.
1 Map<ID, Contact> m = new Map<ID, Contact>([SELECT Id, LastName FROM
Contact]);
208. How to query and abort scheduled job using Apex.
1 List<CronTrigger> abort_job = [SELECT Id FROM CronTrigger
limit 1];
2 for (CronTrigger t : abort_job) { //for each record
3 System.abortJob(t.Id); //abort the job
4 }
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 {
5 xhr.setRequestHeader("Authorization", 'Bearer {!$API.Session_ID}');
6
7 },
8 headers : {'Content-Type' : 'application/json; charset=utf-8'},
9 url: postUrl,
1
0
data: postData,
1
1
dataType: 'text'
1
2
})
1
3
.done(function( data ) {
1
4
//Code if success
1
5
})
1
6
.fail(function(xhr,textstatus,error){
1
7
//Code if fail
1
8
});
210. How to create Chatter post from Apex.
1 //Adding a Text
post
2 FeedItem post = new
FeedItem();
3 post.ParentId = oId; //eg. Opportunity id, custom object id..
4 post.Body = 'Enter post text here';
5 insert post;
6
7 //Adding a Link
post
8 FeedItem post = new
FeedItem();
9 post.ParentId = oId; //eg. Opportunity id, custom object id..
1
0
post.Body = 'Enter post text here';
1
1
post.LinkUrl =
' http://www.someurl.com ';
1
2
insert post;
1
3
1
4
//Adding a Content
post
1
5
FeedItem post = new
FeedItem();
1
6
post.ParentId = oId; //eg. Opportunity id, custom object id..
1
7
post.Body = 'Enter post text here';
1
8
post.ContentData =
base64EncodedFileData;
1
9
post.ContentFileName =
'sample.pdf';
2
0
insert post;
read all about chatter and Apex here .
-------------------------------------------------------------------------------------------------------------------------------
----
=======================================================================
-------------------------------------------------------------------------------------------------------------------------------
---
Link 2
1. What is App in Sales force?
An app is a group of tabs that work as a unit to provide functionality. Users can
switch between apps using the Force.com app drop-down menu at the top-right
corner of every page.
You can customize existing apps to match the way you work, or build new apps by
grouping standard and custom tabs.
Navigation to create app in Sales force : Setup ->Build ->Create->App-> Click on
new and create your application according to your requirements.
2. What is object in Sales force?
Custom objects are database tables that allow you to store data specific to your
organization in salesforce.com. You can use custom objects to extend
salesforce.com functionality or to build new application functionality.
Once you have created a custom object, you can create a custom tab, custom
related lists, reports, and dashboards for users to interact with the custom object
data. You can also access custom object data through the Force.com API.
Navigation to create object in sales force: Setup->Build->Create->Object-> Click on
new object and create object according to your requirement.
3. How many relationships included in SFDC & What are they?
We are having two types of relationships, they are
Lookup Relationship
Master-Detail Relationship
4. What is a “Lookup Relationship”?
This type of relationship links two objects together,
Up to 25 allowed for object
Parent is not a required field.
No impact on a security and access.
No impact on deletion.
Can be multiple layers deep.
Lookup field is not required.
5. What is “Master-Detail Relationship”?
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 of the Child records.
Up to 2 allowed to object.
Parent field on child is required.
Access to parent determines access to children.
Deleting parent automatically deletes child.
A child of one master detail relationship cannot be the parent of another.
Lookup field on page layout is required.
6. How can I create Many – to – Many relationship?
Lookup and Master detail relationships are one to many relationships. We can
create many – to – Many relationship by using junction object. Junction object is a
custom object with two master detail relationships.
7. A custom object contains some records, now my requirement is to create field in
this object with master detail relationship. Can we create master detail
relationship in this case?
No, directly we cannot create master details relationship if custom object
contains existing records.
Following are the steps to create to create master-detail relationship when
records are available in custom object.
1. First create field with lookup relationship.
2. And then associate look field with parent record for every record
3. Next change the data type of the field from look up to Master detail.
8. List examples of custom field types?
Text, Pick list, Pick list (multi select), Date, Email, Date/Time, Date, Currency,
Checkbox, Number, Percent, Phone, URL, Text Area, Geolocation, lookup
relationship, master detail relationship etc…..
9. What is TAB in Salesforce?
Tab is a user interface component to user creates to display custom object data.
There are three type of tabs.
Custom Tabs
Visual force Tabs
Web Tabs
10. Does user can create insert their own custom logo, while creating their own
custom applications?
Yes user can upload their custom logo in documents and then they choose that
logo for organization.
11. List things that can be customized on page layouts?
We can customize different things on page layout like, Fields, Buttons, Custom
Links and Related Lists. We can also create sections.
12. What is a “Self Relationship”?
Self Relationship is a lookup relationship to the same object. Suppose let’s take an
object “Merchandise”. Here we can create relationship in between the Account to
Account (same object) object. That is called “Self Relationship”.
13. What are the main things need to consider in the “Master-Detail Relationship”?
Record level access is determined by the parent, Mandatory on child for reference
of parent, cascade delete (if you delete the parent, it can cascade delete the child).
14. What is difference between trigger and workflow?
Workflow
Workflow is automated process that fired an action based on Evaluation criteria
and rule criteria.
We can access a workflow across the object.
We cannot perform DML operation on workflow
We cannot query from database
Trigger
Trigger is a piece of code that executes before or after a record is inserted or
updated.
We can access the trigger across the object and related to that objects
We can use 20 DML operations in one trigger.
We can use 20 SOQL’s from data base in one trigger.
15. What is Wrapper class?
A Wrapper class is a class whose instances are collection of other objects.
It is used to display different objects on a Visual Force page in same table.
16. What is Difference between SOQL and SOSL?
SOQL(Salesforce Object Query Language)
Using SOQL we can Search only on one object at a time.
We can query on all fields of any datatype
We can use SOQL in Triggers and classes.
We can perform DML operation on query results.
SOSL(Salesforce object Search Language)
Using SOSL we can search on many objects at a time.
We can query only on fields whose data type is text,phone and Email.
We can use in calsses but not in Triggers.
We cannot perform DML operation on search result
17. What is difference insert() and database .insert() ?
Using insert method we can insert the records but if any error occurs in any record
system will throw an error insertion fail and none of the records are inserted.
If we want to execute partially success of bulk insert operation we will use
database .insert.
18. What is Static Resources?
Using Static Resources we can upload images, zip files, jar files, java script and
CSS files that can be referred in a visual force page.
The maximum size of Static Resources for an organization is 250mB.
19. How to call java script using Static Resource in Visual Force page?
Add java script file in Static Resource setup -> develop -> Static Resources -> click
on ‘New’ -> Name: filename and add file from local desktop and save.
We can use that file as follows in Visual Force page
<apex: includescript values=” {! $Resource.fileName}”/>
20. What is sharing rule?
If we want to give the access to other users we use sharing rules.
21. How many ways we can share a record?
Role Hierarchy:
If we add a user to a role, the user is above in the role hierarchy will have read
access.
Setup -> manage users -> roles -> setup roles -> click on ‘add role’ -> provide name
and save.
OWD:
Defines the base line setting for the organization.
Defines the level of access to the user can see the other user’s record
OWD can be Private, Public Read Only, Public Read and Write.
Setup -> Security Controls -> sharing settings -> Click on ‘Edit’
Manual Sharing:
Manual Sharing is sharing a single record to single user or group of users.
We can see this button detail page of the record and this is visible only when OWD
setting is private.
Criteria Based Sharing rules:
If we want to share records based on condition like share records to group of users
Whose criteria are country is India.
Setup -> security controls -> sharing settings -> select the object and provide name
and
Conditions and save
Apex sharing:
Share object is available for every object(For Account object share object is
AccountShare ). If we want to share the records using apex we have to create a
record to the share object.
22. What are the actions in workflow?
1. Email Alert
2. Task
3. Field Update
4. Outbound Message
Go through the below link for the more information about workflow actions
http://www.salesforcetutorial.com/salesforce-workflow-automation-workflow-ma
nagement/
23. How many ways we can made field is required?
1. While creation of field
2. Validation rules
3. Page Layout level
24. What is difference between Role and Profile?
Role is Record level access and it is not mandatory for all users.
Profile is object level and field level access and it is mandatory for all users.
25. What is the maximum size of the PDF generated on visualforce attribute
renderAs?
15MB
26. How many controllers can be used in a visual force page?
Salesforce come under SAAS so, we can use one controller and as many
extension controllers.
27. What is difference between Action support and Action function?
Action function: Invoke the controller method from java script using AJAX and we
can use action function from different places on visual force page.
Action support: Invoke the controller method using AJAX when even occurs on
page like onMouseOver, onClick, ect… and we can use action support for particular
single apex component.
28. How many ways we can call the Apex class?
1. Visual force page
2. Web Service
3. Triggers
4. Email services
29. How to create Master Details relationship between existing records?
Directly we can’t create Master Detail relationship between existing records, first
we have to create Lookup relationship and provide valid lookup fields and it
shouldn’t null.
30. What is permission set?
Permission sets extend user’s functional access without changing user’s
profile.
Ex: A user has only read access through profile on custom object, administrator
want to give access Edit and create operations to him without changing the profile.
Administrator creates the permission set having edit and creates operation on
custom object and assign to that user.
31. What is manual sharing?
Manual sharing is to share a record to a particular user manually.
Go to detail page of record and click on manual sharing button and assign that
record to other user with Read or Read/Write access.
Manual Sharing button enables only when OWD is private to that object.
32. How we can change the Grant access using role hierarchy for standard objects?
Not possible.
33. What is the use of “Transfer Record” in profile?
If user have only Read access on particular record but he wants to change
the owner name of that record, then in profile level Transfer Record enables he
can able to change the owner.
34. What is Field dependency?
According to the field selection on one field filter the pick list values
on other field.
35. Is check box performs like controlling field?
Yes possible. Controlling field should be Check box or pick list.
36. How many field dependencies we can use in Visual Force page?
Maximum we can use 10 field dependencies in VF page.
37. What is Roll-up summary?
Roll-up displays the count of child records and calculate the sum, min and
max of fields of the child records.
38. How to create Roll-up summary field on lookup relation?
Not possible. Roll-up summary is enabled for only Master –Detail
relationship.
39. What are the Record Types?
Record Types are restrict the pick list values and assign to the different
page layouts for different Record Types.
40. What is Audit Trail?
Audit Trail provides the information or track all the recent setup changes
that an administrator done to the organization.
This can store the last 6 months data.
41. What are the Report Types?
4 Types of report in Salesforce
Tabular Reports: We can only displays the grand total in the table form.
Summary Reports: It is a detail form of report in which the grouping done
based on Columns.
Matrix Reports: It is a detail form of report in which the grouping done based
on both Rows and Columns.
Joined Reports: We can join the two or more reports in the single report
displayed in the form of blocks.
42. What is Dashboard?
Dashboard is a pictorial representation of report. We can add up to 20
reports in single dashboard.
Link 3 : Coding challenges
Link 4: Good
1) Explain what is sales force?
Salesforce is a CRM delivered as a software-as-a-service (SaaS).
2) Explain what is a custom object in sales force?
Custom objects are nothing but database tables. It stores data related to your company
in Salesforce.com. Once you have defined custom object you can do following things like
● Create custom fields
● Associate the custom object with other records
● In custom related lists, it display the custom object data
● For custom object, records track events and tasks
● Build page layouts
● For the custom object create a custom tab
● To analyze custom object data create dashboards and reports
● Share your custom tabs, custom apps, custom objects and any other related
components
3) Explain what is object relationship overview?
Object relationship overview in Salesforce is used to link custom object records to
standard object records in a related list. In simple words, it is helpful to track product
defects associated with customer cases. You can define different types of relationship by
creating custom relationship fields on an object.
4) Mention changing what may cause data loss?
Data loss may cause due to following reasons
● Changing data and date-time
● Altering to percent,number and currency from other data types
● Changing from multi-select picklist, checkbox, auto number to other types
● Altering to multi-select picklist from any type except picklist
● Changing to auto-number except from text
● Changing from text-area to e-mail, phone, URL and text
5) How SaaS can be helpful to Sales force?
● As SaaS is a subscription based, customers can always choose not to renew if
they are dissatisfied
● Customers can avoid a large initial investment in an IT infrastructure and day to
day hustle of maintaining infrastructure
● SaaS customer provides same provider infrastructure and also easy integration
● SaaS applications use a simple internet interface that makes easier for customer
to use.
● SaaS always provide a latest platform to the customer with innovation.
6) How sales force is useful in tracking sales?
Sales force records all the basic details like the number of customers served daily, daily
sales volume, sales manager detailed reports, sales numbers in each month or quarter.
Also, it keeps a track on the repeat customer, which is key to success for any sales
organization.
7) Mention how many relationship is included in SFDC and what are they?
There are two types of relationships
● Master detail relationship
● Lookup relationship
8) Mention what is the difference between isNull and isBlank?
● isNull: It supports for number field
● isBlank: It supports for Text field
9) Explain what is the trigger?
Trigger is a code that is executed before or after the record is updated or inserted
10) Mention what is the use of the static resource in Salesforce?
With the help of static resources, you can upload zip files, images, jar files, JavaScript
and CSS files that can be referred in a visual force page. The optimum size of static
resources for an organization is 250 mB.
11) Mention what is the difference between force.com and Salesforce.com?
Force.com is PaaS (Platform as a Service) while Salesforce.com is SaaS ( Software as a
Service).
12) Mention what are the actions available in workflow?
Actions available in workflow are
● Email Alert
● Task
● Field Update
● Outbound Message
13) Explain what is the limit of data.com records that can be added to Salesforce?
User can see their limit form setup, by clicking data.com administration/Users. From the
data.com users section, user can see their monthly limit and how many records are
exported during the month.
14) Mention what are the different types of custom settings in Salesforce?
Different types of custom settings in Salesforce includes
● Hierarchy type
● List type
15) Mention what are the three types of object relations in Salesforce?
Different types of object relations in Salesforce includes
● One to many
● Many to many
● Master detail
16) Mention what are the different types of reports available in Salesforce?
Different types of reports available in Salesforce are
● Tabular report: It displays the grand total in the table form
● Matrix report: It is a detailed report in which the grouping is done based on both
rows and columns
● Summary report: It is a detailed form of the report in which the grouping is done
based on columns
● Joined report: With this two or more reports can be joined in the single reports
17) Is it possible to schedule a dynamic dashboard in Salesforce?
No, it is not possible to schedule a dynamic dashboard in Salesforce.
18) What does it indicate if an error state this “list has no rows for assignment”?
The error that tells “list has no rows for assignment” indicates that the list you are trying
to access has no values in it.
19) Explain what the junction object is and what is the use?
Junction objects are used to build many-to-many relationships between objects. You
can take a recruiting application example, where a position for a job can be linked to
many candidates and in the same manner a candidate can be linked to the different
positions. So, to connect this data model, you need a third party object, this object is
referred as junction object. Here “job application” is the junction object.
20) Explain what is Audit trail?
Audit trail function is helpful in knowing the information or track all the recent setup
changes that the administration does to the organization. It can store last 6 months data.
21) Explain what is dashboard?
Dashboard is the pictorial representation of the report, and we can add up to 20 reports
in a single dashboard.
22) Explain how many controllers can be used in a visual force page?
As Salesforce comes under SaaS, one can use only one controller and as many
extension controller.
23) Mention what is the difference between SOQL and SOSL?
SOQL ( Salesforce Object Query
Language)
SOSL (Salesforce Object Search
Language)
● Only one object at a time can be
searched
● Query all type of fields
● It can be used in triggers and
classes
● DML operation can be performed
on query results
● Many objects can be searched at
a time
● Query only e-mail, phone and text
● It can be used in classes but not
in triggers
● DML operation cannot be
performed on search result
Link 5 : Good
Link 6 : Good
Other links:
http://theblogreaders.com/salesforce-interview-questions-and-answer/#.VkDO4F66T2M
http://theblogreaders.com/salesforce-interview-questions-and-answer/#.VkDO4F66T2M
http://www.salesforcetutorial.com/configuration-customization/
https://salesforcedev401.wordpress.com/2013/09/18/interview-questions-for-salesforce-d
eveloper/ :EXcellent
https://www.quora.com/What-are-some-of-the-best-Salesforce-and-Salesforce1-interviewquestions-
for-new-learners-as-well-as-experienced-professionals
===================================================================
Note :-
1)Users
Personal Edition - 1
Contact Manager - 5 - 5000 Chatter Free
Group Edition - 10 - 5000 Chatter Free
Professional Edition - Unlimited - 5000 Chatter Free
Enterprise Edition - Unlimited - 5000 Chatter Free
Unlimited and Performance Edition - Unlimited - 5000 Chatter Free
Developer Edition - 2 - 5000 Chatter Free
2)API Requests Limits
Developer Edition - 5
Trial organizations - 5
Production organizations -25
Sandbox - 25
--------------------------------------------------------------------------
Links
https://intellipaat.com/interview-question/salesforce-interview-questions/?utm_sourc
e=salesforce%20interview%20linkedin_SM&utm_medium=posting&utm_campaign=
salesforce%20interview%20linkedin_SM%2Fposting
Batch apex
http://blog.shivanathd.com/2013/01/how-to-write-batch-class-in.html
In order for us to write batch classes in apex, let us 1st understand what is batch
class , when and where it should be used? This is an extensive blog going into
details.
Main sections of this post are
1. What is batch Apex
2. When to use batch apex
3. Advantages of using batch apex
4. Batch Apex Governor limits
5. Sample Code
What is Batch Apex ?
Batch as the name suggests, is used when a large data (bulk) volume is involved
and it has to be redundantly processed using a particular logic.
The Batch apex, can be used to conveniently perform time to time task and some
real complex job ranging from data cleansing, archiving the data to the other quality
improvements.
When to use Batch Apex?
The typical use of batch apex is when you want to do a bulk job, but if you do it in a
regular apex you’re bound to hit the governor limits. Batch Classes process the set
of records you pass to it in batches of maximum 200 per batch. To learn more about
the governor limits go here , or you can check out the presentation at slideshare
below
Advantages of using Batch Apex?
Higher Governor Limits
Can be used to process in batches
Can be scheduled to run at different time. ( read more )
Work around to other governor limits e.g. Send More than 10 E-mails blog by Ankit
Arora
here is the governor limit difference in using batch
Area Normal Context Batch Context
SOQL queries 100 SOQL per
cycle
200 SOQL per cycle
records retrieved by SOQL
queries
50,000 50,000,000
(getQueryLocator)
executed code statements 200,000 1,000,000 (Winter '14)
Heap size 6 MB 12 MB
Batch Apex Governor Limits
These are the governor Limits you need to keep in mind when dealing with Batch
Apex
● Up to five queued or active batch jobs are allowed for Apex.
● A user can have up to 50 query cursors open at a time. For example, if 50
cursors are open and a client application still logged in as the same user
attempts to open a new one, the oldest of the 50 cursors is released. Note
that this limit is different for the batch Apex start method, which can have up
to five query cursors open at a time per user. The other batch Apex methods
have the higher limit of 50 cursors. Cursor limits for different Force.com
features are tracked separately. For example, you can have 50 Apex query
cursors, 50 batch cursors, and 50 Visualforce cursors open at the same time.
●
● A maximum of 50 million records can be returned in the
Database.QueryLocator object. If more than 50 million records are returned,
the batch job is immediately terminated and marked as Failed.
● If the start method returns a QueryLocator, the optional scope parameter of
Database.executeBatch can have a maximum value of 2,000. If set to a
higher value, Salesforce chunks the records returned by the QueryLocator
into smaller batches of up to 2,000 records. If the start method returns an
iterable, the scope parameter value has no upper limit; however, if you use a
very high number, you may run into other limits.
● If no size is specified with the optional scope parameter of
Database.executeBatch, Salesforce chunks the records returned by the start
method into batches of 200, and then passes each batch to the execute
method. Apex governor limits are reset for each execution of execute.
● The start, execute, and finish methods can implement up to 10 callouts each.
● Batch executions are limited to 10 callouts per method execution.
● The maximum number of batch executions is 250,000 per 24 hours.
● Only one batch Apex job's start method can run at a time in an organization.
Batch jobs that haven’t started yet remain in the queue until they're started.
Note that this limit doesn't cause any batch job to fail and execute methods of
batch Apex jobs still run in parallel if more than one job is running.
Sample Code
Batch Class :
global class ExampleBatchClass implements Database.Batchable<sObject>{
global ExampleBatchClass(){
// Batch Constructor
}
// Start Method
global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);
}
// Execute Logic
global void execute(Database.BatchableContext BC, List<sObject>scope){
// Logic to be Executed batch wise
}
global void finish(Database.BatchableContext BC){
// Logic to be Executed at finish
}
}
Call the Batch Class :
?
1
2
3
ExampleBatchClass b = new
ExampleBatchClass();
//Parameters of
ExecuteBatch(context,BatchSize)
database.executebatch(b,10);
Note : if batch size is not mentioned it is 200 by default.
That’s about it for this post, if you still want a deep dive into Batch Classes I suggest
you read this
Do let me know your thoughts Happy Coding !
================================================
Insert parent and child using a single insert call
Account acc=new Account(Name='Blog Acc 8', Master_Id__c='Blog Acc 8');
Contact cont=new Contact(FirstName='Bob', LastName='Buzzard', Account=new
Account(Master_Id__c='Blog Acc 8'));
insert new List<Sobject>{acc, cont};
================================================
http://www.slideshare.net/developerforce/df121306-ready
https://www.developerforce.com/guides/Visualforce_in_Practice.pdf
One Top MNC Asked These Interview Questions On Saturday(9/1/16).
Please Try To Answer These Questions.
1.What are the stranded objects you work with……………?
2.How do you query a product object ….?
Lets I want to find out a product with name, xyz so how you will query that….?
3.What is standard controllers, standard list controller and standard set controllers……?
4.On SF page how can we show error message….?
5.How can we connect VF page to word document and pdf….?
6.Can we call a controller from VF page asynchronously…..?
7.What is action function and java script remote action….?
8.How to resolve the view state error….?
9.What is the use of transient keyword ….?
10.Are private variables counted in view state…..?
11.Are static variables counted in view state…..?
12.What are the context variables in apex…..?
13.Why there is no before undelete…..?
14.After undelete will available in which variable….?
15.A & B objects having lookup relation then how can we rollup summary or can we do
coding…..?
16.What is process builder…..?
17.Governor limits…..?
18.What is batch class….?
19.Hop to write batch class, what are pre requisites…..?
20.What are the methods in batch apex…..?
21.What is the return type of start method…..?
22.What is @future method and what are pre requisites of @future methods…..?
23.Can we call @future method from batch class…?
24.Can I call batch class from a batch class from which method….?
25.What are the different annotations….?
26.What is @test.setup annotation….?
27.Governor limits for test class, if any….?
28.What are the different ways of development….?
29.What is the way to deploy using ANT….?
30.How can we remove a class from production….?