Salesforce Interview Questions

Feb 27, 2023

By Admin

Interview Questions

Following are the Salesforce interview questions that are divided into Basic, Intermediate and Advanced levels.

We should not modify the live application directly so we work in different environment for the changes of the existing application.

* Pictorial representation of internet is Cloud.

* Cloud Computing is nothing but internet computing.

*With this approach everything can be done in internet (Using Application, Developing Application and distributing the hardware), no need of any minimum hardware requirements and no need to install any software in local system.

*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)

1. Salesforce is a company which provides a web based tool called Salesforce

2. Salesforce by following the Cloud Computing approach, providing SAAS and PAAS

3. SAAS: Providing Sales, Marketing and Call Center applications as a service

4. PAAS: Providing Force.com platform in which we can develop Apex (Programming language similar to Core Java) and Visualforce (Mark up language similar to HTML) logic.

We should not make coding changes in production since end-users are using the application from production environment.

login.salesforce.com

* Pictorial representation of internet is Cloud.

* Cloud Computing is nothing but internet computing.

test.salesforce.com

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

Using point and click approach, we can configure the functionalities.

* 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 -

3. Task: Task is nothing but work assigned to a particular person, it doesn't have certain time limit.

2. 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 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 realted 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 fieds, if we don't populate with value for number fields it will return true.

* ISNULL() 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), 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 Architecutre - Model, View , Controller

View - It is the user interface (Apps, Tabs, Page Layouts, 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)

* In Salesforce, whenever user create any component (Object, field, tab etc...) or record then salesforce will generate an unique id with which user can identify the record or component.

* After creating the record, in the URL user can see the id of the record which is of 15 digits length.

* Through user interface user always see 15 digit id which is Cases-Sensitive.

* If the user query the existing records from the database through API (Either from Query Tool or from a program), it will always return 18 digit id which is Case-Insensitive.

* Last 3 digits of the 18 digit represents checksum of the capitalization of 15 digit id.

* Based on the first 3 digits user can identify the object of the record.

* All the records belongs to same object will contain same firt 3 digits.

* 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.

Within the sfdc standered functionality (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.

Create a unique text field and update the field from workflow rule (use formula to update by combining two field values), after the update again all the system validations will be performed so error will be displayed..

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

* How many external ids we can enable for an object: 7 (increased from 3 to 7 in Winter-15)

text, number, auto number, email.

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. If we want we can create new views. While creating the view we can give the filter conditions so that based on the filter condition only we can see the records.

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.

On lead and case objects we can create the Assignment rules. Whenever any record is submitted for lead/case if specified condition in the Assignment rule satisfied based on that we can decide the owner of the case/lead. Note: While submitting case/lead we should check for 'Assign using active assignment rule' checkbox which will display under Optional section.

On lead and case objects we can create the Auto-Response Rules. Whenever any record is submitted for lead/case if specified condition in the Auto-Response Rules satisfied based on that we can decide the email format which should send as auto response.

On case object we can create Escalation rule. Based on the priority we can send escalation mails.

To avoid Data Redundency and To achieve Integrity we should go for 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)

Profiles and Permission Sets provides security for meta-data (Structure) components.

No, once we create an user in salesforce we cannot delete the user record. We can only deactivate the user record.

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 :

1. Log in as a user to whom you want to enable Log in access.
2. At top right corner click on name (Which should be left to Setup) > My Settings
3. User should be able to see user's personal set up page.
4. Left side, click on Personal Information > Grant Account Login Access
5. User should be able to see Grant Account Login Access page
6. In Access Duration column select '1 Year' for all the records and click on 'Save' button.
7. Log out and Log in as any other user in the organization then click on Manage Users > Users.
8. User should be able to see list of records and verify the user to whom we enabled the Grant Account Login Access
9. User should be able to see the Login link beside Edit link.
10. Click on Login then user should be able to login as that user mode
11. Observe at top right corner, user should be able to see Logged in as 'Name of the user' which should be highlighte in black color.
12. Click on Logout
13. 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.

* Profile deals with CRED (Create, Read, Edit and Delete) permissions over Apps, Tabs, sObjects, Fields, Record Types, etc...
* We can map only one profile for one user and without mapping the profile we cannot create the user.

* To improve the permissions for the users over profiles we should go for Permission Sets.
* 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)

1. Roles
2. OWD(Organigation Wide Defaults)
3. Sharing Rules.
4. Manual Sharing
5. Apex Managed sharing
6. View all.
7. Modify all.
8. View all data.
9. Modify all data.

Role deals with authorization to access data.

OWD is the default access level on records for any object in sales force. For custom objects we can see below access levels :
1. Private
2. Public Read only
3. 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 every one can have Read/Write permissions on the records.

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.

To process bulk records.

* 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 masterdetail relationship between two objects then child object we can't see).

Data Loader is a stand-alone tool to process bulk records. With Dataloader we can process maximum of 5 million records. Most of the time we use only Dataloader. Default batch size of the Dataloader is 200.

1. Insert (Inserting brand new records, no need of ID)
2. Update (Updating the existing records based on the record ID)
3. 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)
4. Delete (Delete the records based on the id provided, to delete we need only id, deleted records can be found in recycle bin)
5. 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.)
6. 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)
7. 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.

Suppose we have account table in Salesforce and account table outside of the Salesforce (ex: .csv file, sql database). In Salesforce all the records can be identified with record id and outside of the Salesforce we can't recognize records with Salesforce id that is the reason to compare outside table and salesforce table in Salesforce for one of the field we have to enable external ID (we can enable external id for text, number, auto number and email). If we enable external id we can compare that particular column with the column which is available in external table. While comparing if the both column values are same then it will update otherwise it will insert.

10,000 records and minimum 1 record.

2,000 records.

To summarize the information.

To summarize the information of an object we use reports.

1. Tabular (Displays records just like a table)
2. Summary (we can summarize the information based on certain fields)
3. Matrix (we can summarize the information in two dimensional manner, both rows and columns)
4. 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.

We can display up to 2000 records on a page. If more records are there to display we cannot see those through user interface. If you export the records to a excel sheet then you can export up to to 50000 records.

Questions on Apex Basics.

Definitions

Programming Elements

- Variables and Methods comes under Programming Elements

OOP's Concepts

Encapsulation

Binding the PE's into a single unit.

Keywords: class and interface


Abstraction

Different levels of hiding the PE's

Keywords: private,protected,public and global


Polymorphism

Different behavior of the PE's

Keywords: override


Inheritance

Reusing one encapsulation from another encapsulation

Keywords: extends and implements

Apex follows above concepts hence we call apex as a OOP's based language.

1. By default all the variables and methods are non-static.

2. Scope of the non-static variables or metods is within the scope of the same object.

3. We can declare variables and methods as static by using static keyword.

4. Scope of the static variables and methods is through out the transaction.

5. Static variables and methods, we can directly call with class name (we cannot access static variables and methods with object name).

Questions on Collections.

1. List (ordered and allow duplicates)

2. Set (unordered and won't allow duplicates)

3. Map (Key and value pair)

List Set
List is Ordered. Set is unordered.
List allows duplicates. Set doesn't allow duplicates.
We can access list elements with index. Set elements cannot be accessed with index.
We can sort list elements with sort method (default sorting order is ascending). sort method is not available for Set.
We can process records which are stored in list using DML statements(insert, update, delete and undelete). Contains method is available for Set to search for a particular element in the set.
We can process records which are stored in list using DML statements(insert, update, delete and undelete). We can process records which are stored in list using DML statements(insert, update, delete and undelete).

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.

//Syntax: Map mapName = new Map();

/*Map countryISTCodeMap = new Map();

countryISTCodeMap.put('India','91');

countryISTCodeMap.put('USA','001');

countryISTCodeMap.put('India','911');//replaces old value with new value.*/

Map countryISTCodeMap = new Map{'India'=>'91','USA'=>'001', 'India'=>'911'};

system.debug('countryISTCodeMap result: '+countryISTCodeMap+' with size '+countryISTCodeMap.size());

system.debug('countryISTCodeMap keys: '+countryISTCodeMap.keyset());

system.debug('countryISTCodeMap values: '+countryISTCodeMap.values());

system.debug('countryISTCodeMap search: '+countryISTCodeMap.containsKey('India'));

system.debug('countryISTCodeMap fetching value based on key: '+countryISTCodeMap.get('India'));

//map keys are case-sensitive.

1. keyset(): To fetch only keys from the map.

2. values(): To fetch only values from the map.

3. containsKey(value): To search a key from the map.

4. get(key): By supplying the key we can fetch the value.

5. put(key,value): To add key and value in a map.

Questions on DML, SOQL and SOSL.

1. Insert

2. Update

3. Delete

4. Undelete

5. Upsert (Combination of insert and update)

6. Merge (Combination of update and delete)

1. Number of DML statements per transaction: 150 (as a whole including insert, update, delete and undelete)

2. Number of rows processed per DML stmt: 10000

1. SOQL: Salesforce Object Query Language

2. SOQL Purpose: To fetch info. from an object and related objects.

3. We can write query on one object while querying on those objects we can fetch the child object info. or parent object info. (we cannot capture un related objects info.)

4. SOQL queries per transaction: 100.

5. SOQL query rows returned: 50000.

1. SOSL: Salesforce Object Search Language

2. SOSL Purpose:We can search for a value in multiple objects (no need of any relationship).

3. Results of SOSL query can be stored in List of List.

4. SOSL queries per transaction: 20.

5. SOSL query rows returned: 2000.

insert/update Database.insert/Database.update
Assume that you are inserting 100 records. 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. Assume that you are inserting 100 records. If any one of the record fail due to error then it will perform partial operation (valid records will be inserted/updated) if we use Database.insert(list,false)/ Database.update(list,false).
with insert/update if we use try-catch then we can capture only one error which will cause to stop the operation. with Database.insert/Database.update 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];

Questions on 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.

To schedule the batch class we should write a separate class by implementing Schedulable interface.

After writing the above mentioned class 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.

Questions on 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 6 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.

See the below examples -

* 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().

What is the purpose?

To compare Actual value and Expected value we use assert statements.

Types of assert statements

1. system.assertEquals(val1,val2): If both val1 and val2 are same then test class run successfully otherwise test class will fail.

2. system.assertNotEquals(val1,val2): If both val1 and val2 are not same then test class run successfully otherwise test class will fail.

3. 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. 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.

1. 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.

2. While testing apex triggers and batch classes, we should do bulk testing at least with 200 records.

3. We should test for all the positive and negative scenarios.

Questions on 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 java script 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 -

1. Standard Controller
2. 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.

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 :

1. extensions
2. Standard List Controller
3. 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.

A method with the name save exists in all the classes mentioned above. Which will execute first and what is the order?


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.

1. Creation: In a visualforce page, whenever we use form tag then view state will be created for the page.

2. 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, which ever 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.

3. 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:
1. 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.
2. Static variables also won't occupy space in the view state.
3. 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 :

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 :
1. CONFIRM
2. ERROR
3. FATAL
4. INFO
5. 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 will 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 :

1. Using standardSetController
2. 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 :

1. Create an Apex Class say 'MyWrapper'(It can be inside/outside of the controller class.)
2. Declare the necessary variables in the class to store the information.
3. Create a list called 'MyWrapList' for 'MyWrapper'.
4. Create multiple instances for 'MyWrapper' and store it in 'MyWrapList' list.
5. Access 'MyWrapList' list from VF page.

In the below scenarios, we have to go for wrapper class :
1. If you want to display checkboxes along with records so that upon selecting checkboxes corresponding records can be processed (Updating, Delteting, etc.).
2. If you need to display records in single table by combining the columns which belongs to multiple objects.

Custom Label is a memory location where we can store the text.
Where to use?

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 settigns :
1. List Custom Settings
2. Hierarchy Custom Settings

List custom settings :
1. List Custom Settings are like custom objects.
2. We can create the fields and we can store the records.
3. List Custom Settings records will store in Application Cache memory.
4. To access List Custom Settings records no need to use SOQL query.
5. 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 :
1. We can add users and profiles.
2. After that we can check that a particular/current logged in user is part of this custom settings.
3. We can refer this in below components :
   1. Validation Rules
   2. Apex Classes and Apex Triggers
   3. Visualforce Pages

Please find the below differences ;

List Custom Settings Custom Objects
Stores data in Application Cache memory. Stores data in database.
No need to use SOQL query to fetch the records. We 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 few standard buttons with visualforce pages.
To override standard button with visualforce page, VF page should be of 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
1. ?param1=val1 : parameters should start with ? symbol.
2. ¶m2=val2 : To add multiple parameters, each parameter should be separated with & symbol.

Ways of passing parameters :
1. From a VF Page: Whenever we click on commandButtton or commandLink or outputLink, we can pass parameters with param tag. See the below example :
click

2. 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');

3. 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.

4. 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 teh parameters. Click here for the reference.

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 overriden 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.

Like VF page we can create visualforce component. Syntax -
Your code here.

We can use only controller and extensions attribute for the VF component. standardController cannot be used.

When to use VF Component?

1. If you want to reuse the VF page logic.
2. If the VF page logic is huge and if you want to split into different pieces.

We can request VF page in two ways :

1. 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

2. 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

Scenarios on Apex Triggers.

Child__c has a look-up relationship with the object Parent__c. In case of look-up relationship, if we delete the parent objects records then in child object only that look-up value will be removed. Here the requirement is whenever user delete the parent records then all the related child records should be deleted (entire record).


Solution:

pop-uptext

/* Description:

* ============

* Apex Trigger to delete the related child object records upon

* deleting the parent object record in case of look up

* relationship *

* Author:

* ========

* www.srinusfdc.com

*/

trigger ParentTrigger on Parent__c (before delete) {

/*Assume that parent__c is a field api name( look up to parent object)

in child object.*/

delete [select id from Child__c where parent__c in: trigger.old];

/*Note: trigger.old will be automatically converted to set of ids

by salesforce (alternative: trigger.oldMap.keyset()).*/

}

Child__c has two fields Amount and quantitiy. In parent display total amount and total quantity of all the related child records.

Solution:

Prerequisite

Please follow the below steps to proceed with this example.

S.No Component
. Follow the order as mentioned below to create the components
. Configuration
1. Create New App
Singular Label: Parent
Plural Label: Parents
Object Name: Parent
2. Create New Custom Object
Singular Label: Parent
Plural Label: Parents
Object Name: Parent

Standard Field:
Field Label Parent No:
Data Type: Auto Number
Display Format: P-{00000}
3. Create New Custom Object
Singular Label: Child
Plural Label: Childs
Object Name: Child

Standard Field:
Field Label Child No:
Data Type: Auto Number
Display Format: C-{00000}