Salesforce Interview Questions and Answers
Salesforce Interview Questions
Sales force Interview Questions and Answers for beginners and experts. List of frequently asked Salesforce Interview Questions with answers by Besant Technologies.
We hope these Salesforce interview questions and answers are useful and will help you to get the best job in the networking industry. This Salesforce interview questions and answers are prepared by Salesforce Professionals based on MNC Companies expectation. Stay tune we will update New Salesforce Interview questions with Answers Frequently.
Best Salesforce Interview Questions and Answers
Besant Technologies supports the students by providing Salesforce interview questions and answers for the job placements and job purposes. Salesforce is the leading important course in the present situation because more job openings and the high salary pay for this Salesforce and more related jobs. We provide the Salesforce online training also for all students around the world through the Gangboard medium. These are top Salesforce interview questions and answers, prepared by our institute experienced trainers.
Salesforce Interview Questions and Answers for Placements
Here are the list of most frequently asked Salesforce Interview Questions and Answers in technical interviews. These questions and answers are suitable for both freshers and experienced professionals at any level. The questions are for intermediate to somewhat advanced Salesforce professionals, but even if you are just a beginner or fresher you should be able to understand the answers and explanations here we give.
Production and Sandbox Environments
The practice of using a network of remote servers hosted on the Internet to store, manage, and process data, rather than a local server or a personal computer.
Cloud Computing is an approach to provide the following services
- SAAS (Software As A Service)
- PAAS (Platform As A Service)
- IAAS (Infrastructure As A Service)
test.salesforce.com
login.salesforce.com
We should not make coding changes in production since end-users are using the application from production environment.
To make any changes for the exiting application we should copy all contents of the production into sandbox and make all changes after that test thoroughly after that move those changes into production.
To create the sandbox, in production we can find one link called sandboxes. by clicking on that link we can create the sandbox by choosing type of the sandbox.
- Developer Sandbox
- Developer pro sandbox
- Partial data sandbox
- Full copy sandbox
- It copy only configuration changes from the production.
- It won’t copy real time data.
- We can test the configuration changes with sample data.
- Sample data limit is 200mb.
- Refresh time interval is one day.
- If we refresh all the sandbox contents will be replaced with production contents
- Copy configuration changes
- No real time data
- Sample data limit is 1GB
- Refresh time interval one day
- Copy configuration changes
- Copy certain amount of real time data
- Real time data limit is 5GB
- For each table it can copy maximum of 10k records
- Refresh interval 5 days
- It is exact replica of the production
- Copy both configuration and entire real time data from the production
- Refresh time interval 29 days
Customization
While creating the object, we can enable ‘Track Field History’. If, we enable ‘Track Field History’ user can see ‘Set History Tracking’ button under ‘Custom Fields & Relationships’ section which is available on the object detail page. By clicking on ‘Set History Tracking’ button, we can enable tracking for the fields which ever we want. To see the object history, go to object’s record layout and add Object Name History related list to the layout. Whenever, user changes field value from one value to another value, it will show the history of the field in ‘Object History’ related list.
To create the Activities, while creating the object, we should check for ‘Allow Activities’ check box then user can add open Activities and Activity History related lists on the Object layout.
There are two types of activities –
Task: Task is nothing but work assigned to a particular person, it doesn’t have certain time limit.
Event: It has certain time limit in that time only all persons should assemble after the time limit over, event will get complete.
Once event or task status is changed to ‘Completed’, then we can see those records under Activity History Related List.
Tab name will be decided based on the Plural Label of the custom object, to rename go to corresponding object detail page and rename the plural label.
Click on the tab (Which should be related to any of the custom/standard object) > Expand Force.com Quick Access Menu > Edit Columns > Move the needed fields from Available Fields to Selected Fields. > Click on Save > User should be able to see multiple columns.
(OR)
Click on Setup > Create > Objects > Select the corresponding object link > Under Search Layouts section > Click Edit which should be left to Object Tab > Move the needed fields from Available Fields to Selected Fields. > Click on Save > User should be able to see multiple columns.
ISNULL() works only for number data type fields, if we don’t populate with value for number fields it will return true. It won’t support TEXT data type fields because text fields never become null.
ISBLANK() supports both number as well as text data types.
In some scenario’s, we should be able to control one of the field (Dependent field) from another field (Controlling field).
For example: if we select Country (Controlling field) as US then City (Dependent Field) should display only US cities.
We can use checkbox data type fields also while creating dependent picklist (Note: Checkbox should be always controlling field)
We can use multi-select data type fields also while creating dependent picklist (Note: multi-select data type field should be always dependent field)
MVC Architecture – Model, View, Controller
View – It is the user interface (Apps, Tabs, Page Layouts, VF Pages, Fields and Record Types)
Controller – Business Logic (Save, Edit, New, Cancel and Delete – upon click on these button salesforce execute some logic from controller)
Model – It is the Database, which stores Schema (Meta-Data(Data about Data) –> Apps, Tabs, sObjects, fields, Apex Classes, Visualforce pages, etc…) and Instance (Records)
Normally, when a Salesforce user pulls the id from a record through the interface on any object they get the 15 digit id by design. So, if you created a report on Leads / Account / Contacts or any custom object and add the id field through the interface it will look something like 0015000001Fn4VL.
However, if you were to access that same Salesforce account id via an API or a tool like this from the Apex Data-loader & workbench 0015000001Fn4VLAAZ.
The last three digits in the ID are a checksum. A calculation to assure that the first 15 pieces of the ID is accurate for the object it’s being written into.
15 digit ID is case-sensitive.
15 digit ID is what will be received from within the user interface.
18 digit ID case-insensitive and best used for manipulating data outside Salesforce.
18 digit ID is referenced through in the API and other 3rd party tools.
If you would like to convert the current user interface id to 18 digits this can be done by using a formula very simple formula. I have seen a couple of versions of the formula but this is the one that worked best for me in my career.
All you need to do is add a new formula field, text 18 characters with “CASESAFEID(ID)”
For an object based on the Record Type, we can show different fields and different picklist values by assigning different page layouts for the record types and profiles.
After creating the record type, on the record type detail page user can see all the picklist data type fields, user can edit the picklist and decide which values should display for this particular record type.
Whenever user try to create a new record or edit an existing record user can input the values for the fields, this page is nothing but edit page.
After creating a new record or editing an existing record, user can see the information of the record, this page is nothing but detail page.
Functionalities are available within the Salesforce platform (i.e. no need to code).
- Custom tabs (create for objects)
- Web tabs (create to display a website)
- Visual force tabs (create to display the visual force page)
While creating or modifying the record based on the certain conditions we can display error messages on top of the page or below to the filed.
Using vlookup function in the validation rule we can achieve this.
Since we are working in multitenant environment Salesforce is enforcing the limits for all the functionalities.
How many no of fields for an object: 500
No of master detail relationships for an object: 2
No of lookup relationship for an object: 25
No of rollup summery fields: 10
How many external ids we can enable for an object: 7 (increased from 3 to 7 in Winter-15)
Text, number, auto number, email.
List View allows you to see a filtered list of records, such as contacts, accounts, or custom objects.
List views are stored within a Custom Object component. The component can represent a custom object or a standard object, such as an account.
After clicking on the tab on the top of the page we can see views, by default we can see the value called ‘all’. If we click on ‘Go’ beside that all we can see all the records of that object. We can create new views and while creating the view we can give the filter conditions so that based on the filter condition we will be able to see records in tab.
On the detail page without clicking on edit button we can edit particular field if it is not read-only.
To enable or disable Inline editing follow the below navigation – Setup–> Customise–> User Interface–> Enable Inline Editing
In list views we can modify multiple records at a time using Enhanced list views Note: To modify multiple records, all the records should belong to same record type in the list view otherwise we cannot modify.
Whenever we click on a tab or we click on a lookup icon or search for a record we see only one standard field by default, to enable remaining fields –
- To show multiple fields for the records which display under a tab, on object detail page > under Search layouts edit tab and add required fields.
- To show multiple fields for the records which display when we click on lookup of a field, on object detail page > under Search layouts edit Lookup Dialogs and add required fields.
- To show multiple fields for the records which display when we search for the records, on object detail page > under Search layouts edit Search Results and add required fields.
For lookup fields on record detail page we see a link, whenever we put cursor on that link we see a popup window which displays few fields. To control the fields visibility, on that look up field parent object page layout we see a mini page layout in that we can control.
To control the picklist values of the status field on the lead object we should create lead process.
Without selecting the lead process we can’t create the record type for lead object
To control the picklist values of the stage field on the opportunity object we should create sales process.
Without selecting the sales process we can’t create the record type for opportunity object
To control the picklist values of the status field on the case object we should create support process.
Without selecting the support process we can’t create the record type for case object
On lead object we can generate the HTML code by selecting lead fields and by mentioning return URL from web-to-lead option. The generated HTML code can be hosted in any of the website. Upon entering the information in those fields and clicking on submit button that information will be saved into lead object of the Salesforce.
In queue we can add group of users and we can assign the objects to the Queue. After creating the queue one of the list view automatically created on the objects which are selected for the queue. We can assign this queue as the owner of the records (objects which are selected for this queue). Later users who are part of that queue can claim the ownership by navigating to list view corresponding to the queue. In that list view users who are part of the queue can select the record and click on accept button so that record ownership will be transferred from queue to accepted person.
We can add set of random users in the public group. We can’t assign public group as an owner of the record. In manual sharing, sharing rules and in list views we can use public group.
Assignment rules are used to automate your organization’s lead generation and support processes.
Lead Assignment Rules – 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.
Case Assignment Rules – Determine how cases are assigned to users or put into queues as they are created manually, using Web-to-Case, Email-to-Case, On-Demand Email-to-Case, the Self-Service portal, the Customer Portal, Outlook, or Lotus Notes.
Aim: All the cases created by user ‘ABC_User’ should be assigned to ‘XYZ_User’.
An auto-response rule is a set of conditions for sending automatic email responses to lead or case submissions based on the attributes of the submitted record. Applicable leads include those captured through a Web-to-Lead form.
Applicable cases include those submitted through a:
- Self-Service portal
- Customer Portal
- Web-to-Case form
- Email-to-Case message
- On-Demand Email-to-Case message
Create case escalation rules to escalate cases automatically if they are not resolved within a certain period of time.
Typically, your organization will have one escalation rule that consists of multiple entries which specify exactly how the cases are escalated. For example, your standard case escalation rule could have two entries: Cases with Type set to Gold are escalated within two hours, and cases with Type set to Silver are escalated within eight hours.
Goto Setup | Customize | Cases | Escalation Rules.
Relationships
No, we cannot create directly. To create first we should create Look up relationship then populate the field value for all the records and then convert the look up relationship to master detail relationship.
If the parent object doesn’t have Roll up Summary fields for the child object then we can convert.
If the parent objects don’t have Roll up Summary fields for the child object then we can delete. To delete a child object it should not be referred in Apex Classes and Apex Triggers. Later if we undelete the object, Master detail fields on the junction objects will be converted to look up Fields.
Note: If we delete only Master – Detail Relationship field from the child object and undelete it from the Recycle Bin then it will be converted to look up relationship. Parent Object we cannot delete because it will be referred in the child object.
Master – Detail Relationship data types will be converted to look up relationship data types.
If we delete parent object record all the child object records relationship’s field value will be get deleted. (Entire record won’t be get deleted)
Example:
Child Object: Employee (Employee object have Department field which is related to Department Object)
Parent Object: Department
Suppose N number of employee records related to IT department, if we delete IT department all the child (Employee) records Department field value related to IT department will be get deleted.
Note: Salesforce store deleted records only for 15 day in Recycle bin later it will remove the records permanently. If we undelete the IT department record from the Recycle bin then all the related child records department field value will be restored.
If we delete the parent object record all the child object records will be get deleted.
Example:
Child Object: Employee (Employee object have Department field which is related to Department Object)
Master Object: Department
Suppose N number of employee records related to IT department, if we delete IT department all the child records will get deleted.
Note: Salesforce store deleted records only for 15 day in Recycle bin later it will remove the records permanently.
If we undelete the IT department record from the Recycle bin then along with IT department record all the related child (Employee) records will be restored. (We cannot see the child object records in the Recycle bin)
A child object which is having master detail relationships with two different parent object is called junction object.
Example:
Object1: Department
Object2: Project
Child Object: Employee
Field1: Department (Master Detail with Department )
Field2: Project(Master Detail with Project)
Note: From the above example we can say Employee Object as Junction Object.
Child records will be get deleted which are related to Department as well as Project.
Note: If we undelete the IT department record from the Recycle bin then along with IT department record all the related child (Employee) records will be restored those will be reflected for Project as well. (We cannot see the child object records in the Recycle bin)
Users, Profiles and Permission Sets
No, once we create user in salesforce we cannot delete the user record. We can only deactivate the user record.
If you need help resolving a problem, you can grant login access to your account to a Salesforce administrator or a support representative.
If we enable ‘Grant Account Login Access’ for a user then we can see ‘Log in’ button on the detail page of that user. By clicking on that ‘Log in’ button without giving that user’s username and password we can log in.
To enable the ‘Grant Account Login Access’ follow the below steps –
- Log in as a user to whom you want to enable Log in access.
- At top right corner click on name (Which should be left to Setup) > My Settings
- User should be able to see user’s personal set up page.
- Left side, click on Personal Information > Grant Account Login Access
- User should be able to see Grant Account Login Access page
- In Access Duration column select ‘1 Year’ for all the records and click on ‘Save’ button.
- Log out and Log in as any other user in the organization then click on Manage Users > Users.
- User should be able to see list of records and verify the user to whom we enabled the Grant Account Login Access
- User should be able to see the Login link beside Edit link.
- Click on Login then user should be able to login as that user mode
- Observe at top right corner, user should be able to see Logged in as ‘Name of the user’ which should be highlight in black color.
- Click on Logout
- User should be come back to original user’s mode, Observe at top right corner, user should not be able to see Logged in as ‘Name of the user’
Using Profiles and Permission Sets.
A profile is a group/collection of settings and permissions that define what a user can do in salesforce.
A profile controls “Object permissions, Field permissions, User permissions, Tab settings, App settings, Apex class access, Visualforce page access, Page layouts, Record Types, Login hours & Login IP ranges.
We can map only one profile for one user and without mapping the profile we cannot create the user.
Permission set is also very similar to profile. Whatever you can manage at profiles (Like Object permissions, Field Permissions, User permissions, Tab settings, App settings, Apex class permission, visualforce permission) the same you can manage here also.
But the main difference between these two is that user can have only one profile and can have multiple permission sets at time.
Example: To give additional permissions to few users who belongs to different profiles over Apps, Tabs, sObjects and fields.
Permission sets.
1000 (It will depends upon the number of licenses taken by the client, it will be like upto 4000 like that based on the client)
- Roles
- OWD (Organization Wide Defaults)
- Sharing Rules
- Manual Sharing
- Apex Managed sharing
A role hierarchy controls level of visibility that users have to an organization data.
By defining role hierarchies we can share access to records.
Users assigned to roles near the top of hierarchies like (CEO, executives and other higher level roles) get to access the data of all users who fall directly below them i hierarchy.
Organization-Wide Defaults, or OWDs, are the baseline security you for your Salesforce instance. Organizational Wide Defaults are used to restrict access. You grant access through other means we will talk about later (sharing rules, Role Hierarchy, Sales Teams and Account teams, manual sharing, etc).
There are four levels of access that can be set:
Private
Public Read/Only
Public Read/Write
By default after creating custom object OWD access level is Public Read/Write.
Private: only owner and above hierarchy users can have Read/Write access and below hierarchy users don’t have any access.
Public Read only: only owner and above hierarchy users can have Read/Write access and below hierarchy users can have only Read Only.
Public Read/Write: Irrespective of role hierarchy everyone can have Read/Write permissions on the records.
Determine whether users have access to records they don’t own, including records to which they don’t have sharing access, but someone below them in the hierarchy does.
Say there are three roles
- Role A
- Role B
- Role C
Role A is higher in hierarchy, Role B is in middle and Role C is lower in hierarchy
If the Role A user through Manual Sharing or Sharing Rules, shares the record to Role C user who is in lower hierarchy, then the Role B user who is above in hierarchy to Role C user can see the records, if we enable Grant Access Using Hierarchies at sharing settings else Role B user cannot see the record.
Import Wizard and Data Loader
Import wizard is a web based tool to process bulk records. With import wizard we can process maximum of 50,000 records. In import wizard we can’t see few objects (ex: if there is master detail relationship between two objects then child object we can’t see).
Data Loader is a client application for the bulk import or export of data. Use it to insert, update, delete, or export Salesforce records.
When importing data, Data Loader reads, extracts, and loads data from comma-separated values (CSV) files or from a database connection.
When exporting data, it outputs CSV files.
- Insert (Inserting brand new records, no need of ID)
- Update (Updating the existing records based on the record ID)
- Upsert (To Upsert we should have one external ID field on the object, based on the external id field if the value already exists it will update, if doesn’t exist then it will insert)
- Delete (Delete the records based on the id provided, to delete we need only id, deleted records can be found in recycle bin)
- Hard delete (Delete the records based on the id provided, to delete we need only id, deleted records can’t be found in recycle bin, Note: If we enable bulk API in data loader settings then only we can perform Hard delete.)
- Export (From any object we can export records based on the SOQL query, Note: We can’t export deleted records which are there in the recycle bin)
- Export all (From any object we can export records based on the SOQL query, Note: Using Export all we can export deleted records which are there in the recycle bin also)
.CSV (Comma Separated Values)
.SDL
In Dataloader settings we should enable ‘insert null values’ checkbox otherwise we can’t insert null values.
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, 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 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 id.
The maximum value is 10,000 if the Use Bulk API option is selected.
In a single insert, update, upsert, or delete operation, records moving to or from Salesforce are processed in increments of this size. The maximum is 200 records.
2,000 records
Enabling the Bulk API in Data Loader allows you to load or delete a large number of records faster than using the default SOAP-based API.
However, there are some differences in behavior in Data Loader when you enable the Bulk API.
One important difference is that it allows you to execute a hard delete if you have the permission and license.
Workflows and Approvals
- Created
- Created and every time edited to meet the criteria
- Created and edited to subsequently meet the criteria
If we select ‘Created and every time edited to meet the criteria’ whenever we create a record or edit a record if the criteria of the workflow rule meets then it will trigger every time.
If we select ‘Created and edited to subsequently meet the criteria’ – whenever we create the record that meets criteria so that workflow will fire and while editing the record again criteria meets workflow won’t fire (meeting the criteria to meeting the criteria).
When we create the record, if the record criteria don’t meet then the workflow will not fire. In the dame way if criteria meet while editing the record then the workflow will fire.
Conclusion: Previous state of record should be not meeting criteria and current state of record should be meeting the criteria then only in current state workflow will fire.
Criteria meet (field – operator – value, if there are multiple criteria’s then in filter criteria we can give conditions like ( 1 or 2) and 3, field to field comparison is not possible, we can’t fetch the previous state information of the field).
Formula evaluated (we can write formulas with this we can do field to field comparison and we can fetch previous state value of the record).
The action which will be performed immediately after the record criteria meets.
The action which will be performed in future based on the any of the date field. To create time dependent workflow action we should create one time trigger.
In time trigger we can give either days or hours with the maximum of 999 value and we can select either before or after.
Created and every time edited to meet the criteria.
Field update – we can update a field of the same object or the fields of the parent objects which are at master side in master-detail relationship, only for master-detail parent objects we can update the field and for lookup we can’t update.
Email alert – we can send emails if the criteria meets
New task – we can create new task
Outbound Message – we can make a callout
- Text
- HTML (with letter head)
- Custom HTML (without letter head)
- Visual Force
It won’t trigger in the schedule date because if we modify the record to not meeting criteria that queued field update will be removed from the ‘time based flow’ queue.
Yes, it will trigger in scheduled date.
It won’t fire.
To fire wf2 we should enable ‘re-evaluate Workflow Rules’ checkbox of the field update which is there in wf1.
- An approval process is an automated process your organization can use to approve records in Salesforce.
- An approval process specifies the steps necessary for a record to be approved and who must approve it at each step.
- A step can apply to all records included in the process, or just records that have certain attributes.
- An approval process also specifies the actions to take when a record is approved, rejected, recalled, or first submitted for approval.
Before creating the Approval Process we should select the object after that we should follow below steps –
- Give the Approval Process name
- Give the criteria of the Approval Process
- Select the email template – If we don’t select any email template salesforce by default send an email notification to the target approver else with our selected email template target approver will be notified
- Select the users who can submit for the approval – If we do not select any user by default all the users who can access to that record can submit
- Select the user to whom record should be submitted
- Initial submission actions – after submitting the record for approval immediately whatever the actions included in the initial submission actions section will be triggered
- Approval Steps – we can add multiple steps
- For each and every step we can see ‘Approval actions’ and ‘rejection actions’ sections where we can add actions to be performed
- If the Approver approves the record then actions which are under ‘approval actions’ section will be triggered
- Final approval actions section – If all the steps approved then actions which are under ‘final approval actions’ section will be triggered
- Final rejection actions section – If any one of the step rejected then actions which are under ‘final rejection actions’ section will be triggered
- Recall approval actions – After submitting record for approval if you want to revoke we click on recall approval action on the detail page, after clicking on that button actions which are under recall approval actions section will be triggered
It’s not possible, to add one more step deactivate the approval process and clone the deactivated approval process and add the new steps.
Reports and Dashboards
Reports give you access to your Salesforce data.
You can examine your Salesforce data in almost infinite combinations, display it in easy-to-understand formats, and share the resulting insights with others. Before building, reading and sharing reports, review these reporting basics.
- Tabular – Displays records just like a table
- Summary – We can summarize the information based on certain fields
- Matrix – We can summarize the information in two dimensional, both rows and columns
- Join – We can summarize information in different blocks on the same object and the related objects
5 blocks
3 groupings
Bucket field in Reports is used to group values to the name we specify.
Apex Programming Basics
Any language which supports the following concepts are called OOPs based languages.
Encapsulation – Class and Interface – a way to bundle data and capabilities to operate on that data.
Abstraction – providing the appropriate level of information and data at the requested level, with the help of access specifiers (i.e. private, protected, public and global)
Polymorphism – it allows you to define ways of dealing with data without knowing exactly how that data will be defined in the future.
Inheritance – the capability of a class or object to have certain methods and attributes passed down to them through a hierarchy, this we will achieve by using extends and implements keywords.Apex supports all the above mentioned concepts so Apex is OOPs based language.
Note: Apex is Case Insensitive.
By default all the variables and methods are non-static.
Scope of the non-static variables or methods is within the scope of the same object.
We can declare variables and methods as static by using static keyword.
Scope of the static variables and methods is throughout the transaction.
Static variables and methods, we can directly call with class name (we cannot access static variables and methods with object name).
Collections
List – ordered and allow duplicates
Set – unordered and won’t allow duplicates
Map – Key and value pair
LIST | SET |
Ordered | Unordered |
Allows duplicates | Doesn’t allow duplicates |
Can access elements with index | Cannot be accessed with index |
We can sort list elements with sort method – default sorting order is ascending | Sort method is not available |
Contains method is not available | Contains method is available, to search for a particular element |
Can process records which are stored in list using DML statements (insert, update, delete and undelete) | Cannot process records which are stored in set using DML statements |
No limit for the size of a list. It only depends on the heap size which is 6 MB (Synchronous) and 12 MB (Asynchronous).
Map holds key and value pair.
Map keys are case-sensitive.
Syntax: Map<Datatype, Datatype> mapName = new Map<Datatype, Datatype> ();
keyset(): To fetch only keys from the map.
values(): To fetch only values from the map.
containsKey(value): To search a key from the map.
get(key): By supplying the key we can fetch the value.
put(key,value): To add key and value in a map.
DML, SOQL and SOSL
- Insert
- Update
- Delete
- Undelete
- Upsert (Combination of insert and update)
- Merge (Combination of update and delete)
Number of DML statements per transaction: 150 (as a whole including insert, update, delete and undelete)
Number of rows processed per DML statement: 10000
SOQL: Salesforce Object Query Language
SOQL Purpose: To fetch records from an object and related objects.
We can write query on one object while querying on those objects we can fetch the child object records or parent object records
Governor Limits for SOQL statements
SOQL queries per transaction: 100
SOQL query rows returned: 50000
SOSL: Salesforce Object Search Language
SOSL Purpose: We can search for a value in multiple objects (no need of any relationship).
Results of SOSL query can be stored in List<List<sObject>>.
Governor Limits for SOSL statements:
SOSL queries per transaction: 20
SOSL query rows returned: 2000
Assume that you are inserting 100 records.
Insert / Update | Database.Insert / Database.Update |
If any one of the record fail due to error then entire operation will fail. None of the records will be saved into the database, by using insert/update if we use try-catch then we can capture only one error which will cause to stop the operation. | If any one of the record fail due to error then it will perform partial operation (valid records will be inserted/updated) by using Database.insert(list, false)/ Database.update(list, false)
We can capture all the errors by saving result in Database.saveResult[].
|
Queues will store in Group object. To query for MyQueue from the database using SOQL, we should use the following syntax –
Group grp = [select Id, Name from Group where Name = ‘MyQueue’ and Type = ‘Queue’ Limit 1];
Apex Triggers
Before Mode: Before the record is saving into the database, it will fire.
After Mode: After the record is saved into the database (doesn’t commit at this point of time), it will fire.
Before | After |
before insert | after insert |
before update | after update |
before delete | after delete |
after undelete |
Note: before undelete event is not available.
To capture the runtime information we use trigger context variables.
Below context variables will return either true or false.
- Trigger.isBefore – returns true if the trigger context is Before Mode
- Trigger.isAfter – returns true if the trigger context is After Mode
- Trigger.isInsert – returns true if the trigger context is Insert
- Trigger.isUpdate – returns true if the trigger context is Update
- Trigger.isDelete – returns true if the trigger context is Delete
- Trigger.isUndelete – returns true if the trigger context is Undelete
- Trigger.isExecuting – returns true if the apex class method is getting call from Apex Trigger
Below context variables will store records at runtime.
- trigger.old – stores history (old versions) of the records
- trigger.oldMap – stores history (old versions) of the records along with id
- trigger.new – stores new version of the records
- trigger.newMap – stores new version of the records along with id
Apex Trigger Collections availability for the different events –
Events | trigger.old | trigger.oldMap | trigger.New | trigger.NewMap |
before insert | No | No | Yes | No |
after insert | No | No | Yes | Yes |
before update | Yes | Yes | Yes | Yes |
after update | Yes | Yes | Yes | Yes |
before delete | Yes | Yes | No | No |
after delete | Yes | Yes | No | No |
after undelete | No | No | Yes | Yes |
Read/Write access over the trigger collections on different events –
Events | trigger.old | trigger.oldMap | trigger.New | trigger.NewMap |
before insert | NA | NA | Read/Write | NA |
after insert | NA | NA | Read Only | Read Only |
before update | Read Only | Read Only | Read/Write | Read Only |
after update | Read Only | Read Only | Read Only | Read Only |
before delete | Read Only | Read Only | Read Only | Read Only |
after delete | Read Only | Read Only | Read Only | Read Only |
after undelete | Read Only | Read Only | Read Only | Read Only |
Before Triggers – To perform the validations we should use before triggers.
If you are updating any field on the same object on which you are writing the trigger and no need to explicitly include the DML statements (already due to DML operation only trigger fire and it is still in progress at this point of time.)
After Triggers – If you are dealing with relationship records and if you need record id in these situations we should use after trigger (in before insert record doesn’t contain the record id).
We cannot control the order of execution in this situation. It is recommended to have only one trigger per one object.
Note: We can keep the logic of the apex trigger in an apex class and can invoke from that class.
If we perform update operation on the record in after update event logic recursive triggers will arise.
Using static Boolean variable in an apex class (we should not keep static Boolean variable inside of the trigger) we can avoid recursive triggers.
- If we perform DML operation on standard/custom object and global objects (User, User Role, Group, Group Member, Permission Set, etc…) in same transaction this error will come.
- To avoid this error, we should perform DML operation on standard/custom object records in a different transaction.
- In general all the apex classes and apex triggers execute synchronously (execute immediately).
- If we perform DML operation on standard/custom object records asynchronously (execute in future context), we can avoid MIXED-DML-OPERATION error.
- To execute logic asynchronously keep the logic in an apex method (in a separate apex class, not in same apex trigger) which is decorated with @future annotation.
See the below example:
Note: To analyse the code copy it and paste it in notepad for the convenience.
public class TriggerUtility {
- Following future method execute asynchronously (whenever server is free it will execute in future context).
- We should not declare @future method in Apex Trigger.
- @future method should be always static.
- @future method accepts only primitive data types (Integer, String, Boolean, Date, etc…) as parameters and it won’t accept non-primitive data types (sObject,Custom Objects and standard Objects etc.. ) as parameters.
- @future method should not contain return type. Always it should be void.
- From an apex trigger we can make only make asynchronous call outs. To make call out we should include “callout = true” beside the future @annotation.
- We cannot perform synchronous call outs from Apex Trigger.
//Below is the example for the future method –
@future(callout = true)
public static void processAsync(primitive parameters) {
//Logic to insert/update the standard/custom object.
}
}
- ChildObject__c
- ParentObject__c
Relationship between ChildObject__c and ParentObject__c objects is Lookup relationship.
In case of lookup relationship if we delete the parent object record in child object only the relationship field value will be removed (child records won’t be deleted).
But client has a requirement to delete the child object records. How to achieve this?
Write an apex trigger to achieve this functionality.
We should take before delete event. If we take after delete relationship will broke up b/w parent and child object records.,
Trigger ParentTrigger on ParentObject__c(before delete) {
/*
Note:
– For delete events only trigger.old and triggger.oldMap will be available.
– trigger.old holds old versions of the records but if we mention that in SOQL query salesforce will automatically convert those records into ids.
*/
List childLst = [select id, Parent_Object__c from ChildObject__c where Parent_Object__c in: trigger.old];
delete childLst;
}
- We are creating validation rules, workflow rules, assignment rules, auto-responsive rules, escalation rules and apex triggers etc..
- If the condition is same for all the rules which will execute first and which will execute next, for this salesforce provide the order.
Order of execution in sales force
Prepare the record for insert/update operation.
It will replace all the old field values with new field values.
If the request is coming form UI all the system validations will execute –
- DataType
- Length
- Required
- Unique
- PageLayout level validations
- Before triggers
Custom Validations and again system validation rules will fire (Page Layout level validations won’t fire at this point of time)
Record will be saved into the database but doesn’t not commit.
- After triggers
- Assignment rules
- Auto-responsive rules
- Workflow Rules
In case of Workflow Rule Field updates again before triggers and after triggers fire one more time
- System validation rules for duplicate check
- Escalation Rules
- Rollup-Summary fields will be calculated
- Grant parent Rollup-Summary fields will be calculated
- Criteria base sharing evaluation
- Record will be committed into the database
- Post commits logic (Sending emails)
Validation rules will fire first then workflow rules will fire. So, the answer is 100 (Even though there is a validation rule because of the workflow rule it will accept 100 in the amount field).
There is a workflow rule which will fire if amount > 100 and will update amount field to 100. One of user saved the record by giving value as 1000.
It will throw the validation error because after the workflow field update before triggers fire one more time.
Batch Apex
We can call the apex code by creating object for the class (or) if the variables or methods are static then we can call with class name.
Apex Code in the trigger will execute automatically for the DML operations.
If you want to execute apex code on a specific time then we should write batch class.
With Batch Apex we can process maximum of 50 million records.
Batch Apex is asynchronous (execute in future context).
While writing the batch class we should inherit Database.Batchable interface.
Database is a built in global class which contains inner global interface.
Since we are inheriting Database.Batchable interface we should implement all the method prototypes declared in the interface.
We should implement the following global methods –
start: It will prepare the records to process and execute only one time.
execute: It will take the records prepared in start method and split those records into batches and it will execute multiple times. For example if the start method is returning 1000 records then execute method executes 5 times if you don’t mention the batch size (Default Batch Size is: 200). Maximum batch size is: 2000.
finish: We can perform post commit logic like sending emails with the success or error information. It will execute only one time.
Batch Class Syntax:
//Database is Class provided by Salesforce.
//Batchable is an global interface which is inside of the Database class.
//Batchable include 3 method prototypes: 1. start 2. execute 3. finish
//start and finish methods will execute only one time.
//execute method executes multiple times.
global class BatchUsage implements Database.Batchable , Database.Stateful {
//at a time we can inherit multiple interfaces but we cannot inherit multiple classes.
//By default batch class is stateless (variable info. store in one method cannot be remembered in other method),
//to make it stateful we should inherit Database.Stateful interface.
String name = ”;
global Database.queryLocator start(Database.BatchableContext bc) {
//From asynchronous to asynchronous we cannot call
//(from batch class we cannot call future mehthod vice versa.).
name += ‘start’;
system.debug(‘@@@Start Method: ‘+name);
//Collects the records to process. It will forward these records to execute method.
//If we use Iterable as return type for this start method it can hold
//max. of 50k records only.
//If we use Database.queryLocator as return type for this start method it can hold
//max. of 50 million records.
return Database.getQueryLocator(‘select id, name, Location__c from Department__c where Location__c = \’\”);
}
global void execute(Database.BatchableContext bc, LIST sObjLst) {
name += ‘execute’;
system.debug(‘@@@Execute Method: ‘+name);
//Split the records forwarded by start method into batches.
//Default batch size is: 200.
//Max. batch size is: 2000.
List depUPdLst = new List();
for(SObject sObj: sObjLst) {
Department__c dept = (Department__c) sObj;//Type Casting.
dept.Location__c = ‘Bangalore’;
depUPdLst.add(dept);
}
if(depUPdLst.size() > 0)
update depUPdLst;
}
global void finish(Database.BatchableContext bc) {
name += ‘finish’;
system.debug(‘@@@Finish Method: ‘+name);
//Post Commit logic like sending emails for the success or failures of the batches.
AsyncApexJob a = [select id, Status, NumberOfErrors, JobItemsProcessed,
TotalJobItems, CreatedBy.Email from AsyncApexJob where id =: bc.getJobId()];
Messaging.singleEmailMessage mail = new Messaging.singleEmailMessage();
mail.setToAddresses(new String[]{a.CreatedBy.Email});
mail.setSubject(‘Batch Class Result’);
mail.setHtmlBody(‘The batch Apex job processed ‘ + ” + a.TotalJobItems + ” +
‘ batches with ‘+ ” + a.NumberOfErrors + ” + ‘ failures.’);
//sendEmail methods
Messaging.sendEmail(new Messaging.singleEmailMessage[]{mail});
/*** Scheduling in minutes or hours ***/
/*//Create object for schedulable class
SchedulableUsage su = new SchedulableUsage();
//Preparing chron_exp
Datetime sysTime = System.now();
sysTime = sysTime.addminutes(6);
String chron_exp = ” + sysTime.second() + ‘ ‘ + sysTime.minute() + ‘ ‘ +
sysTime.hour() + ‘ ‘ + sysTime.day() + ‘ ‘ + sysTime.month() + ‘ ? ‘ + sysTime.year();
System.schedule(‘Dep Update’+sysTime.getTime(),chron_exp, su);*/
}
}
To schedule the batch class we should write a separate class by implementing Schedulable interface.
After writing the above mentioned classes to schedule navigate to: Develop > Apex Classes > Schedule Apex.
By clicking on Schedule Apex button we can schedule the batch class through user interface.
Note: Through user interface we cannot schedule in hours/minutes.
Schedulable Class Syntax:
global class SchedulableUsage implements Schedulable {
global void execute(SchedulableContext sc) {
BatchUsage bu = new BatchUsage();
//Database.executeBatch(bu);//Default Batch Size is: 200.
Database.executeBatch(bu,1500);//Max. Batch Size is: 2000.
}
}
To schedule the batch class in minutes/hours, in the finish method we should use System.schedule method which will take 3 parameters Job Name, Chrone Expression and schedulable class instance name respectively.
/*** Scheduling in minutes or hours ***/
//Create object for schedulable class
SchedulableUsage su = new SchedulableUsage();
//Preparing chron_exp
Datetime sysTime = System.now();
sysTime = sysTime.addminutes(6);
String chron_exp = ” + sysTime.second() + ‘ ‘ + sysTime.minute() + ‘ ‘ +
sysTime.hour() + ‘ ‘ + sysTime.day() + ‘ ‘ + sysTime.month() + ‘ ? ‘ + sysTime.year();
System.schedule(‘Dep Update’+sysTime.getTime(),chron_exp, su);
By default batch class is stateless (variable value which is stored in one method cannot be remembered in another method).
To maintain the state for the batch class, we should inherit Database.Stateful interface.
Scenario: In a set list of emails are stored in execute method. In the finish method that set is not having any emails. What is the reason?
Answer: By default batch class is stateless. Emails which are added to set can be remembered only in execute method. If we try to access the set in finish method you won’t see those emails. In finish method if you want to access those emails of that set we should inherit the interface called Database.Stateful.
Yes it is possible, starting with Apex saved using Salesforce API version 26.0, you can call Database.executeBatch or System.scheduleBatch from the finish method. This enables you to start or schedule a new batch job when the current batch job finishes.
For previous versions, you can’t call Database.executeBatch or System.scheduleBatch from any batch Apex method. Note that the version used is the version of the running batch class that starts or schedules another batch job. If the finish method in the running batch class calls a method in a helper class to start the batch job, the Salesforce API version of the helper class doesn’t matter.
We cannot call one asynchronous process from another asynchronous process.
Since @future method and Batch Class both are asynchronous we cannot call future method from batch class or we cannot call batch class from the future method.
To cover the code for the batch class we should call the batch class from the inside of the Test.startTest() and Test.stopTest().
Test.startTest();
//Call the batch class from here.
Test.stopTest();
Up to 5 batch jobs can be queued or active.
By implementing Database.Batchable and Schedulable interfaces we can implement the methods in a same class.
Though it is possible it is not recommended to write like this.
Test Classes
After developing an apex class or apex trigger we should write the unit tests and ensure that we are able to execute at least 75% of the lines of code.
If you are moving the code from sandbox to sandbox regarding code coverage you won’t face any issue.
If you are moving the code from sandbox to production, you need to include all the test classes at the time of deployment and salesforce will run all the test classes which you included for the deployment as well as test classes which are already present in production, if the code coverage is less than 75% deployment will fail.
We cannot write test code (test methods) inside of the apex trigger.
From API Version 28.0, we cannot write the test methods inside of an apex class which is not decorated with @isTest.
We can write test methods only in a class which is decorated with @isTest.
Note: We have a governor limit for the overall Apex Code size of the organization which is of 3 MB. If we decorate a class with @isTest annotation Apex Code Size governor limit will be bypassed.
@isTest
private class MyTestClass {
static testMethod void myTest1() {
}
static testMethod void myTest2() {
}
}
Note: Test Class can be either public or private.
By default test class cannot recognize the existing data in the database.
If you mention @isTest(seeAllData = true) then test class can recognize the existing data in the database.
From a List Custom Settings we cannot fetch the existing data without seeAllData = true in test class.
Suppose you have a custom object called ‘CustomObject__c’ and it contains many records, we cannot fetch the existing data without seeAllData = true in test class.
Note: It is not recommended to use seeAllData = true for a test class. Based on the existing data in database code coverage will impact.
Test.startTest() and Test.stopTest() maintains fresh set of governor limits. Assume that you are consuming 99 SOQL queries outside of Test.startTest() and Test.stopTest() then if you include any SOQL inside of Test.startTest() and Test.stopTest() count will start from 1.
Per testMethod we can use Test.startTest() and Test.stopTest() only for one time.
To execute asynchronous methods synchronously we can call those methods from inside of Test.startTest() and Test.stopTest().
By default test class runs in System Mode. If you want to execute a piece of code in a certain user context then we can use system.runAs (UserInstance). For more details refer 2nd question in visualforce category.
To avoid MIXED-DML-OPERATION error we can include DML statements inside of system.runAs(), still the error persists keep DML statements inside of Test.startTest() and Test.stopTest().
To compare Actual value and Expected value we use assert statements.
Types of assert statements
system.assertEquals(val1,val2): If both val1 and val2 are same then test class run successfully otherwise test class will fail.
system.assertNotEquals(val1,val2): If both val1 and val2 are not same then test class run successfully otherwise test class will fail.
system.assertEquals(val1> val2): If the condition satisfied then test class run successfully otherwise test class will fail.
Sometimes we cannot satisfy certain if conditions for the apex classes, in those situations on those if conditions we can add Test.isRunningTest separated with or condition.
For example: if (condition || Test.isRunningTest())
Sometimes in test classes we need to access a variable from Apex Class, if it is private we cannot access for that we will replace private with public.
For this reason we are compromising the security. To avoid this before the private variables in apex class we can include @TestVisible so that even though variable is private we can access from the test class.
We should not depend on the existing data in the database. We should create the test data for all the possible scenarios.
Note: Profiles and recordTypes cannot be created programmatically, we can query from the database. For the remaining objects including users we should create the test data.
While testing apex triggers and batch classes, we should do bulk testing at least with 200 records.
We should test for all the positive and negative scenarios.
Visualforce Basics
Previously Visualforce Pages were not there, instead S-Controls were there.
S-controls have been superseded by Visualforce pages. Organizations that haven’t previously used s-controls can’t create them. Existing s-controls are unaffected, and can still be edited.
S-controls: It is a combination of HTML and S-control but with this to achieve saelsforce look and feel, it is very difficult and consume lot of tags.
Visualforce: With visualforce we can easily achieve the salesforce look and feel by consuming very few tags.
Browsers (IE, Chrome, Firefox, etc…) can understand only HTML, Visualforce will be converted to HTML before display on the browser by salesforce.
Visualforce page should start with the following syntax –
System Mode: Current logged in user permissions (Object-level, Field-level, Record-level security) won’t be considered. Even though user doesn’t has access, it will provide full permissions.
User Mode: Current logged in user permissions (Object-level, Field-level, Record-level security) will be considered.
See the following table –
Component – Default Mode
Apex Class – System Mode
Apex Trigger – System Mode
standardController – User Mode
controller – System Mode
Extensions (standardController) – User Mode
Extensions (controller) – System Mode
Anonymous Block – User Mode
Note: to apply security for Apex Class, we can use with sharing while declaring the class. With sharing will apply only Record-level security. It won’t apply Object-level and Field-level security.
There are the two types of controllers –
- Standard Controller
- Custom Controller
Note: On a visualforce page, we can use either standardController (attribute name for Standard Controller) or controller (attribute name for Custom Controller). We cannot refer both at a time.
StandardController –
We can refer any standard object or custom object in this attribute. At a time we can refer only one object and we cannot refer apex class in this attribute. standardController by default works in user mode.
Custom Controller –
We can refer any apex class in this attribute. At a time we can refer only one apex class in this attribute. Controller by default works in system mode.
Other supported attributes for the controllers –
Extensions
Standard List Controller
Custom List Controller
Extensions –
We can refer this attribute along with standardController or controller attribute.
In extensions attribute, we can refer multiple apex classes. We cannot refer standard/custom objects.
Standard List Controller –
There is no such attribute called standard list controller but in the standardController page if you mention recordsetVar attribute then that page we can call it as standard list controller page.
In recordsetVar attribute we can give any name which will hold the list of records of the object which we mentioned for the standardController.
Custom List Controller –
There is no such attribute called custom list controller but in the controller page if we display multiple records then that page we can call it as custom list controller.
In controller class, we have to query the records from the database to display the records on the page.
First of all it will give priority for the extensions, in case there are multiple classes referred then it will give priority from left to right after that only it will check in main controller (either standardController or controller).
In the above scenario, it will invoke the save method from ClassA.
Creation: In a visualforce page, whenever we use form tag then view state will be created for the page.
Purpose: Assume that, we need to display the user input form in 3 different visualforce pages. In first and second pages, user has to fill the information and click on Next button. On the final page, after filling the form if he/she will click on save button, whichever the information we filled in the first and second pages should be also saved. View state will store the information which is filled in first and second page. To maintain the state of the page, we need view state.
Size: All the variables which we use in controller/extensions classes and expressions which are declared on the page will occupy the space in view state.
Governor Limits: Maximum size of the View State is: 135 KB.
Page Performance: Whatever the variables information we don’t required to maintain the state while navigating to other pages those variables we can decorate with transient keyword which won’t occupy space in the view state.
Static variables also won’t occupy space in the view state.
It is recommended to use only one form tag. If there are multiple form tags hierarchy of the folder structure increases which will occupy more space.
To store the following kind of files and refer on the visualforce page –
- images
- javaScript/jQuery
- CSS Style Sheets
- zip files
Overall size of the static resources per organization: 250 MB
Size of the each static resource file: 5 MB
To refer the static resource on the VF page use: $Resource.FileName
To refer the zipped static resource on the VF page use: URLFOR($Resource.zipname, ‘/images/FileName.png’)
Please find the following differences –
Static Resources | Documents |
Static Resource is cached at server side | Documents will store in database |
Static Resources can be referred with file name | Documents should be referred with url |
On VF page we should use –
<apex:pageMessages ></apex:pageMessages>
In Apex Class, we should use –
ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.Error,’Error Message’));
Note: For the standardController no need to include code inside of the Apex Class.
Following severity levels are available –
- CONFIRM
- ERROR
- FATAL
- INFO
- WARNING
On a standardController page to display the multiple records we use recordSetVar (without the support of any extensions class).
dataTable: Display the records without standard salesforce look and feel.
pageBlockTable: Display the records with standard salesforce look and feel.
1000
For the page tag we can enable readOnly attribute value as true so that –
Number of query rows will increased from 50000 to 1 million rows.
Number of records displayed on VF page can be increased from 1000 to 10000
inputText: Always display the field as text box irrespective of data types (Checkbox, Picklsit, Look up).
inputField: Display automatically according to the fields data types.
Note: We cannot refer primitive data types (String etc.) with inputField.
outputText: Always display the field value as text irrespective of data types (Currency, Look up, URL etc.)
outputField: Display automatically according to the fields data types.
If it is currency then it will append currency symbol while displaying on the page. If it is look up type then it will display as a link.
Assume that we need to display 100 records on the page.
If the requirement is to display only 10 records at a time –
First: Displays first set of 10 records.
Previous: Displays previous set of 10 records.
Next: Displays next set of 10 records.
Last: Displays last set of 10 records.
We can achieve the above functionality with Pagination. We can achieve the pagination in two ways –
- Using standardSetController
- Using Limit and Offset keywords in SOQL query
Wrapper Class is nothing but list of instances of a certain class.
Follow the below steps to create the Wrapper list –
Create an Apex Class say ‘MyWrapper'(It can be inside/outside of the controller class.)
Declare the necessary variables in the class to store the information.
Create a list called ‘MyWrapList’ for ‘MyWrapper’.
Create multiple instances for ‘MyWrapper’ and store it in ‘MyWrapList’ list.
Access ‘MyWrapList’ list from VF page.
In the below scenarios, we have to go for wrapper class –
If you want to display checkboxes along with records so that upon selecting checkboxes corresponding records can be processed (Updating, Deleting, etc.). If you need to display records in single table by combining the columns which belongs to multiple objects
We can refer in below components –
Validation Rules and Formula fields
Apex Classes and Apex Triggers
Visualforce Pages
What is the advantage?
Assume that you are referring a Record Type Name multiple times in an apex class; in future if the client asked to rename the record type then in all the palaces we need change by searching which consume good amount of time.
To avoid that if you store the Record Type Name in custom label and refer that custom label in all the places.
If you need to change the name in future then you need to change only in that custom label.
Assume that you are displaying an error message on the visualforce page; in future if the client asked to change the error message then it will be a code change.
For code change it requires lot of approvals from business which consume lot of time.
If you keep the error message in a custom label and refer on the page, in future it won’t be a code change, in production directly they can replace the error message in that custom label.
There are two types of custom settings –
- List Custom Settings
- Hierarchy Custom Settings
- List custom settings:
- List Custom Settings are like custom objects.
We can create the fields and we can store the records.
List Custom Settings records will store in Application Cache memory.
To access List Custom Settings records no need to use SOQL query.
Example: Based on the regions, zip codes should be retrieved. In this case, If you store these records in a custom object every time we need to query from the database. Instead if you store the records in List Custom Settings, without consuming SOQL query we can capture the information from the database.
Hierarchy custom settings:
We can add users and profiles.
After that we can check that a particular/current logged in user is part of this custom settings.
We can refer this in below components –
Validation Rules
Apex Classes and Apex Triggers
Visualforce Pages
Custom Settings | Custom Objects |
Stores data in Application Cache memory | Stores data in database |
No need to use SOQL query to fetch the records | Need to use SOQL query to fetch the records from the database |
Limited data types are available when compared to Custom Object | All the data types will be available |
We cannot create validation rules and apex triggers on List Custom Settings | We can create |
We cannot create tab for List Custom Settings | We can create |
rendered: Accepts true or false. If it is true then component will display on the page, if it is false then it won’t display on the page.
reRender: To refresh certain area of a page based on component id.
renderAs: Used in page tag, We can display VF page in PDF format if we give renderAs = “PDF”.
contentType: Used in page tag, we can download VF page in MS Word/Excel etc. based on the input to contentType.
We can override the behavior of standard buttons — like New, View, or Edit — in Salesforce Classic, Lightning Experience, and mobile independently.
We can override few standard buttons with visualforce pages.
To override standard button with visualforce page, VF page should use standardController to an object which is related to standard button.
Custom buttons we can override with URL, javaScript or Visualforce.
On a record detail page we can embed visualforce pages.
Assume that you are displaying inline VF page on Account record detail page. VF page should be standardCotnroller to Account Object.
Note: We cannot embed VF page inside of the Edit page.
Whenever we click on Back or Cancel button on a VF page if there are mandatory fields then we will see the error messages saying to populate those field values.
To bypass validations upon clicking on a button/link, we can use immediate attribute.
Parameters Example: /apex/SamplePage?param1=val1¶m2=val2
?param1=val1 – parameters should start with ? symbol
¶m2=val2 – To add multiple parameters, each parameter should be separated with & symbol.
Ways of passing parameters –
From a VF Page: Whenever we click on commandButtton or commandLink or outputLink, we can pass parameters with param tag.
See the below example –
<apex:commandButton action=”{!Increment}” value=”Increment” reRender=”result”>
<apex:param assignTo=”{!amount}” value=”10″/>
</apex:commandButton>
From pageReference: Upon calling an action method while returning pageReference we can append parameters.
See the below example –
PageReference nextpage = new PageReference(‘/apex/SamplePage’);
nextpage.getParameters().put(‘param1′,’val1’);
nextpage.getParameters().put(‘param2′,’val2’);
- Assume that there are three VF pages which are using the same Apex Class. In this case no need to pass the parameters from one page to other to hold the information.
- Assume that there are three VF pages which are using three different Apex Classes. In this case to hold information from one page to other, we should pass the parameters.
- We cannot override Save button. When you are on record edit page upon clicking on Save button if you want to navigate it to a specific URL, then we need to append saveURL=someURL parameter to the URL.
- You will come to this edit page if you click on ‘New’ or ‘Edit’ button which can be overridden with VF page, from this page you can pass saveURL parameter to edit page.
- When you are on record edit page upon clicking on Cancel button if you want to navigate it to a specific URL, then we need to append retURL=someURL parameter to the URL.
Salesforce provides a library of standard, pre-built components, such as <apex:relatedList> and <apex:dataTable>, that can be used to develop Visualforce pages. In addition, you can build your own custom components to augment this library.
Similar to the way you can encapsulate a piece of code in a method and then reuse that method several times in a program, you can encapsulate a common design pattern in a custom component and then reuse that component several times in one or more Visualforce pages.
<apex:component>
<apex:attribute name=”myattribute” type=”String” description=”TODO: Describe me”/>
<!– Begin Default Content REMOVE THIS –>
<h1>Congratulations</h1>
This is your new Component: mynewcomponent
<!– End Default Content REMOVE THIS –>
</apex:component>
If you want to reuse the VF page logic, then we can use VF Components. If the VF page logic is huge and if you want to split into different pieces, then we can use VF Components.
We can request VF page in two ways –
Get Request: Whenever we click on a link or button or directly hitting the url in address bar we can open a VF page. Get Request Order
Postback Request: On a VF page after populating fields if you click on save button certain action will invoke it is nothing but postback request. Postback Request Order
Q163. What are the types of Ajax Functions in VF page and what is the usage?
There are around 5 AJAX functions –
- actionSupport –this component is used to invoke actions like Javascript, HTML input fields to a controller used for visualforce pages.
- actionStatus –this component is used to notify the status of an asynchronous actions and can also be used to notify when the action starts and when the action stopped..
- actionFunction –this component is used to call method in a controller as a JavaScript function and can also be used anywhere in the visualforce page to call action which include custom JavaScript code.
- actionPoller –this component refreshes the connection regularly, keeping login sessions alive.
- actionRegion – an area of a Visualforce page that demarcates which components should be processed by the Force.com server when an AJAX request is generated. Only the components in the body of the <apex:actionRegion> are processed by the server, thereby increasing the performance of the page.
Part – B Salesforce Interview Questions and Answers
- Developer Sandbox
- Unlimited Edition
- Partial Copy Sandbox
- Developer Edition
- As a String with each value separated by comma;
- As a Set<String> with each value as an element in the set
- As a List<String> with each value as an element in the list.
- As a String with each value separated by semi colon.
Q166. What is a good practice for a developer to follow when writing triggers?
- Using @future methods to perform DML operations
- Using the map data structure to hold query results by ID
- Using the set data structure to ensure distinct records.
- Using synchronous callouts to call external systems.” open=”no” style=”default” icon=”plus” anchor=”” class=””]
Ans: 2
- Namespace
- Time
- Exception
- Debug statement
Ans: 2
- Generate a link using HYPERLINK() function to a specific record in a legacy system
- Display the previous value for a field using PRIORVALUE() function
- Retrurn and display a field value from another object using VLOOKUP() function
- Determine if the DateTime field has passed using NOW()
- Determine which if the three images tos display using IF() function
Ans:3
- debug(‘Amount of CPU time (in ms) used so far: ’+Limits.getCpuTime());
- List<Contact> contacts = [Select Id, Salutation, FirstName, LastName, Email from Contact where Account Id = :a.Id];
- if(o.AccountId == a.Id)
- update contactList;
Ans:2
- Parallel blocks can use the same variable names
- A variable can be defined at any point in the block
- Sub-blocks cannot reuse a parent block’s variable name
- Sub-blocks can reuse the parent block’s variable name if it’s value is null.
- A static variable can restrict the scope to the current block if its value is null.
Ans:3
Q171. When loading data into an organization, what can a developer to match records to update existing records?
- Match an auto generated number field to a column in the imported file
- Match an external id text field to a column in the imported file
- Match the name field to a column in the imported file
- Match the ID field to a column in the imported file.” open=”no” style=”default” icon=”plus” anchor=”” class=””]
Ans:2
- Developer Edition to Sandbox
- Sandbox to Production
- Sandbox to Sandbox
- Developer Edition to Production
Ans:2
- Javascript controller actions
- Third party web service code
- Third party JavaScript code
- Visualforce controller actions
Ans:2
- A single SObject
- An integer
- A String
- A list of SObjects
- A Boolean
Ans:3
- Better integration with force.com sites
- More pre-built components to replicate Salesforce look and feel
- More centralized control via server-side logic
- Better performance for custom Salesforce mobile apps
public class myController
{
Public String myString;
Public String getMyString() {
Return ‘getMyString’;
}
Public String getStringMethod1 (){
Return myString;
}
Public String getStringMethod2(){
If(myString == null)
myString = ‘Method2’;
returnmyString;
}
}
<apex:page controller = “myController”>
{!myString}, {!StringMethod1}, {!StringMethod2}, {!myString}
</apex:page>
- getMyString, , Method2, getMyString
- , , Method2, getMyString
- , , Method2,
- getMyString, , ,
- Any user with a higher role hierarchy
- User who is assigned as the current approver
- Any user who dropped the record previously
- An Administrator
Ans:2
- They use an all or none deployment model
- They require a deployment connection
- They can be used to transfer contact records
- They can be used to deploy custom setting data
- They can be used only between related organizations.
Ans:3
List<Account>acc = [SELECT Id FROM Account LIMIT 10];
Delete Acc;
Database.emptyRecycleBin(acc);
System.debug(Limits.getDMLStatement() + ‘, ‘+Limits.getLimitDMLStatements());
- 2, 150
- 150, 2
- 11, 150
- 150, 11
- Query for test data using setAllData = true. Call the method being tested. Verify that the results are correct.
- Query for test data using setAllData = true. Execute runAllTests(). Verify that the results are correct.
- Create data for testing. Call the method being tested. Verify that the results are correct.
- On opportunity using Opportunity Product records.
- On Account using Case records
- On Quote using Order records
- On Campaign using Campaign member records
- On Account using Opportunity records.
Ans:3
the developer creates following code block:
List<Property__c>propertiesToCreate = helperClass.createProperties();
try{
} catch (Exception exp)
{
//Exception Handling
}
- insert(propertoesToCreate, false);
- Insert propertiesToCreate;
- Insert(propertiesToCreate, System.ALLOW_PARTIAL);
- Insert(propertiesToCreate);
- Executing methods for negative test scenarios
- Loading the Standard Pricebook ID using a system method
- Loading test data in place of user input for Flows
- Executing method as different users.
- To generate a PDF document with application data
- To create components for dashboards and layouts
- To deploy components between two organizations
- To modify page layout setting for a custom object.
Ans:2
- On the monitored user’s name
- The show more link on the debug log’s record
- The log filter tab on a class or trigger detail page
- The filters linked by monitored user’s name within the Web UI.
Ans:2
Salesforce is one of the best & effective CRM (Customer Relationship Management) product delivered as an affordable SaaS( Software as a Service) to the subscribers.
Governor limits are considered as the biggest challenge for the Salesforce developers. Salesforce came with a concept called Governor limits to ensure there should be no single clients monopolizing the shared resources. There are various governor limits while considering Salesforce namely
- com Platform Apex Limits
- Size-specific Apex limits
- Email Limits
- Per-Transaction Apex Limits
- Static Apex Limits
- Miscellaneous Apex Limits
- Push Notification Limits
The Salesforce offers cloud-based solutions and CRM software which helps the organization to connect with the customers in a good way. It helps in supporting the business as well as control the data of the customers and also tracks the data and activities efficiently.
The significant subsidiaries of salesforce include
- Pardot
- Mulesoft
- SalesforceIQ
- Tableau
- Heroku
- Demandware Inc
The database tables are considered to be the objects in salesforce and they are used for storing the organization data. There are two types of objects in salesforce namely
- Custom object: it includes the changes that users made on the salesforce. It stores the relevant, unique, and essential organization data. Custom objects involve object relationships, custom fields, page layouts, custom user interface tab, and more.
- Standard object: It is said to be the salesforce objects that involve accounts, leads, campaigns, contracts, contacts, opportunities, cases, products, dashboards, and more.
- Salesforce Dev 401: The IT and software professionals can learn analytical functions, developing, customised applications, and more to receive an annual salary of US$99,000.
- Salesforce Adv Dev 501: The system administrators, CRM and App developers can learn Developer consoles, apex scripts, deploying MVC architecture, and more to receive an annual salary of US$141,000.
Some of the advantages of Salesforce CRM include
- Deploy the approach in an analytical way to customer acquisition.
- Reduced tasks and repetitive automation.
- Ensures better and faster opportunity in sales.
- Enhances customer satisfaction
- Decreased cost
- Improved communication on all fronts
- Enhanced efficiency
A sandbox is considered to be the product organisation or environment copy that is used for development and testing process. It’s effective as it enables apex programming development without making any disturbance in the production environment. Few types of sandbox include
- Developer Pro
- Full
- Developer
- Partial Copy
An app in salesforce is defined as the container which includes different aspects like name, required tabs, logo, and more. It’s also otherwise known as a group of tabs which work in an integrated way to prove the aspects you are looking for. It’s easy to customise apps in the salesforce to match the expectations. You can also combine standard and custom tabs to develop new applications. The procedure of developing an app in salesforce is as follows.
Setup→ develop→ create→ app→ click on new.
There are two different types of apps that can be created in SF namely
- Console App: In this app, they are used in the client service business. It deals with finding a solution to the issue of the client. It’s not mostly preferred when compared to the custom apps.
- Custom App: Every business can use this custom app in any scenario. It is the most preferred app in the salesforce by business professionals.
It’s easy to link custom object and standard object records in a relevant list. It is executed by the object relationship. Different type of relationship is created to connect different business cases with their respective customers. Its easier to build a custom relationship on any objects and it defines the variety of relationship types. There are three types of object relationship in SF namely
- One to many
- Many to many
- Master-detail
Master-Detail relationship is considered to be the parent-child relationship. The master indicated the parent and the detail indicates the child. If the parent is getting deleted then the child also gets deleted with the parent. The fields of Rollup Summary is created on this type of master-detail relationship with is capable of calculating the MIN, AVG, and SUM of the child records.
- The child compulsory needs the parent field.
- The child is deleted automatically when the parent field is deleted.
- The maximum of 2 is allowed to object.
- Parent access indicates access to children.
- A page layout requires a lookup field.
In this type of relationship, its easy to link two different objects together.
- The parent is not considered as a mandatory field.
- No impact made on the deletion
- There is no requirements for lookup field.
- There can be 25 characters included in the object.
- There is no impact made on access and security
- Can include different layers deep.
Roles are added optionally whereas profiles are considered to be the mandatory basic requirements needed to set up a user. Profiles help in controlling Create, Read, Edit, Delete (CRED) and other object privileges. It also involves system permission that the user carries like data export.
When considering roles, it is used for sharing records across different enterprises. It provides users with the record access that is owned by the people and works in a hierarchical fashion.
SQQL stands for Salesforce Object Query Language. It is identical to Structured Query Language to question databases. It is developed to salesforce information and is utilized for questioning the salesforce platform to receive data. SQQL is utilized within the Visualforce and Apex to return data sets.
Visualforce can be directly customised in the production whereas Apex cannot be directly customised in the production org rather it can be changed and then deployed via the sandbox and also should meet the test coverages.
There are plenty of reasons for the data loss in Salesforce. Some of them include
- Migration of currency, number and percent from other data types changing to the multi-select list from other types except for picklists.
- Altering to auto-number except for text.
- Altering the information and date-time.
- Altering from the checkbox, auto number, and multi-select picklist to other types.
- Altering to phone, text, URL, and email from the text area.
Salesforce is one of the effective tracking programs which records different personal pieces of information like
- Daily sales volume
- Sales figures by quarter or monthly
- Number of customers served daily
- In-depth reports from sales manager
- Salesforce monitor, tracks, and report customer activity repeatedly, it’s an important element for any sales enterprise.
It’s one of the codes which acts with the database nearly and implemented after or before the record is inserted or updated.
One of the automated process that is utilized to validate rule criteria and evaluation criteria.
- isBlank: It enables and supports text field.
- isNull: It enables and supports number field.
There are many actions available in the workflow. Some of them include
- Task
- Outbound message
- Email alert
- Field update
There are two important custom settings available in Salesforce namely
- List type
- Hierarchy type
- Matrix report: it’s an in-depth reporting where the reporting is performed based on the columns and rows.
- Joined report: With two or more reports, it can be joint in the single report.
- Tabular report: It displays completely in the form of tabular format.
- Summary report: it’s also a detailed report in which the grouping is performed based on columns.
A dashboard is considered to be the imagery identification of the report. You can add a maximum of 20 reports in a single dashboard.
Only one controller can be used under SaaS but you can make use of the extension controllers.
The code can be deployed in the salesforce using the methods like
- Salesforce package
- Eclipse with Force.com IDE
- Change sets
- Com Migration tool
There are three types of bindings namely
- Action bindings: it indicates the action methods located in the controller
- Data bindings: it indicates the data set used in the controller.
- Component bindings: it indicates different visualforce components.
- Record ownership
- Apex managed to share
- Manual sharing/user-managed sharing
- com Managed sharing
- Role hierarchy
- Sharing results
- From JavaScript Link
- From another class
- Using triggers
- From developer console
- From homepage components
- From visual force page
In this blog, we Besant Technologies have listed out the top 200+ Salesforce interview questions and answers. Our trainers have researched and analyzed these questions from various top MNC companies and corporate companies. Use these common Salesforce interview questions to help you prepare succinct, relevant answers that convince employers you are best for the job. Preparing yourself with your own material will make you a strong interviewee and the desired employee.
We hope these Salesforce interview questions and answers are useful and will help you to get the best job in the networking industry. These Salesforce interview questions and answers are prepped by Salesforce Certified Professionals based on MNC Companies’ expectations. Stay tuned we will Keep updating New Salesforce Interview questions with Answers Frequently. If you want to learn Practical Salesforce Training then please go through this Salesforce Training in Chennai & Salesforce Training in Bangalore.