Frequently Asked Apex Interview Questions Part – 3
How To Restrict Any Trigger To Fire Only Once?
Triggers can fire twice, once before workflows and once after workflows.
“The before and after triggers fire one more time only if something needs to be updated, If the fields have already been set to a value, the triggers are not fired again.”
Workaround:
public class HelperClass {
public static boolean firstRun = true;
}
trigger affectedTrigger on Account (before delete, after delete, after undelete) {
if(Trigger.isBefore){
if(Trigger.isDelete){
if(HelperClass.firstRun){
Trigger.old[0].addError(‘Before Account Delete Error’);
HelperClass.firstRun=false;
}
}
}
}
What Are Global Variables Explain With Examples?
Global variables are the variables used to reference the general information about the current user or your organization on a page.
Example:
Global variables must be referenced using Visualforce expression syntax to be evaluated, for example, {!$User.Name}.
List of available global variables are as below:
1. $Action
2. $Api
3. $Component
4. $ComponentLabel
5. $CurrentPage
6. $Label
7. $Label.Site
8. $ObjectType
9. $Organization
10. $Page
11. $Profile
12. $Resource
13. $SControl
14. $Setup
15. $Site
16. $User
17. $UserRole
18. $System.OriginDateTime
19. $ User.UITheme and $User.UIThemeDisplayed
How To Create Many To Many Relationships Between Object?
Creating Many to Many relationship in salesforce is little tricky. You cannot create this type of relationship directly. Follow below steps to create this type of relationship.
Create both objects which should be interlinked.
Create one custom object (also called as junction object), which should have auto number as unique identification and create two master relationships for both objects, no need create tab for this object.
Now on both objects, add this field as related list.
In Which Sequence Trigger And Automation Rules Run In Salesforce.com?
The following is the order salesforce logic is applied to a record.
1. Old record loaded from database (or initialized for new inserts)
2. New record values overwrite old values
3. System Validation Rules
4. All Apex “before” triggers (EE / UE only)
5. Custom Validation Rules
6. Record saved to database (but not committed)
7. Record reloaded from database
8. All Apex “after” triggers (EE / UE only)
9. Assignment rules
10. Auto-response rules
11. Workflow rules
12. Escalation rules
13. Parent Rollup Summary Formula value updated (if present)
14. Database commit
15. Post-commit logic (sending email)
Additional notes:
There is no way to control the order of execution within each group above.
What Is S-control?
S-Controls are the predominant salesforce.com widgets which are completely based on Javascript. These are hosted by salesforce but executed at client side. S-Controls are superseded by Visualforce now.
What Is A Visualforce Page?
Visualforce is the new markup language from salesforce, by using which, We can render the standard styles of salesforce. We can still use HTML here in Visualforce. Each visualforce tag always begins with “apex” namespace.
All the design part can be acomplished by using Visualforce Markup Language and the business logic can be written in custom controllers associated with the Page.
Will Visual Force Still Supports The Merge Fields Usage Like S-control?
Just like S-Controls, Visualforce Pages support embedded merge fields, like the {!$User.FirstName} used in the example.
What Are Merge Fields? Explain With Example?
Merge fields are fields that we can put in Email templates, mail merge templates, custom link or formula fields to incorporate values from a record.
Example:
{!CustomObject.FieldName__c}
Where To Write Visualforce Code?
You can write the code basically in 3 ways.
1. setup->App Setup->Develop->Pages and create new Visulaforce page.
2. Setup -> My Personal Information -> Personal Information -> Edit check the checkbox development mode. When you run the page like this, https://ap1.salesforce.com/apex/MyTestPage.you will find the Page editor at the bottom of the page. You can write you page as well as the controller class associated with it, there itself.
3. Using Eclipse IDE you can create the Visulaforce page and write the code.
What Is Difference In Isnull And Isblank?
ISNULL:
Determines if an expression is null (blank) and returns TRUE if it is. If it contains a value, this function returns FALSE.
Text fields are never null, so using this function with a text field always returns false. For example, the formula field
IF(ISNULL(new__c) 1, 0) is always zero regardless of the value in the New field. For text fields, use the ISBLANK function instead.
Multi-select picklist fields are never null in s-controls, buttons, and email templates, so using this function with a multi-select picklist field in those contexts always returns false.
Empty date and date/time fields always return true when referenced in ISNULL functions.
Choose Treat blank fields as blanks for your formula when referencing a number, percent, or currency field in an ISNULL function.
Choosing Treat blank fields as zeroes gives blank fields the value of zero so none of them will be null.
Merge fields can be handled as blanks, which can affect the results of components like s-controls because they can call this function.
When using a validation rule to ensure that a number field contains a specific value, use the ISNULL function to include fields that do not contain any value. For example, to validate that a custom field contains a value of ’1,’ use the following validation rule to display an error if the field is blank or any other number: OR(ISNULL(field__c), field__c<>1)
ISBLANK:
Determines if an expression has a value and returns TRUE if it does not. If it contains a value, this function returns FALSE.
Use ISBLANK instead of ISNULL in new formulas. ISBLANK has the same functionality as ISNULL, but also supports text fields.
Salesforce.com will continue to support ISNULL, so you do not need to change any existing formulas.
A field is not empty if it contains a character, blank space, or zero. For example, a field that contains a space inserted with the spacebar is not empty.
Use the BLANKVALUE function to return a specified string if the field does not have a value; use the ISBLANK function if you only want to check if the field has a value.
If you use this function with a numeric field, the function only returns TRUE if the field has no value and is not configured to treat blank fields as zeroes.
How To Schedule A Class In Apex?
To invoke Apex classes to run at specific times, first implement the Schedulable interface for the class, then specify the schedule using either the Schedule Apex page in the Salesforce user interface, or the System.schedule method.
After you implement a class with the Schedulable interface, use the System.Schedule method to execute it. The scheduler runs as system: all classes are executed, whether the user has permission to execute the class or not.
The System.Schedule method takes three arguments: a name for the job, an expression used to represent the time and date the job is scheduled to run, and the name of the class.
Salesforce only adds the process to the queue at the scheduled time. Actual execution may be delayed based on service availability. The System.Schedule method uses the user’s time zone for the basis of all schedules. You can only have 25 classes scheduled at one time.
Example Code:
String CRON_EXP = ‘0 0 * * * ?’;
clsScheduledHourly sch = new clsScheduledHourly();
system.schedule(‘Hourly Sync’, CRON_EXP, sch);
What Are Different Apis In Salesforce.com?
REST API:
REST API provides a powerful, convenient, and simple REST-based Web services interface for interacting with Salesforce. Its advantages include ease of integration and development, and it’s an excellent choice of technology for use with mobile applications and Web projects. However, if you have a large number of records to process, you may wish to use Bulk API, which is based on REST principles and optimized for large sets of data.
SOAP API:
SOAP API provides a powerful, convenient, and simple SOAP-based Web services interface for interacting with Salesforce.You can use SOAP API to create, retrieve, update, or delete records. You can also use SOAP API to perform searches and much more. Use SOAP API in any language that supports Web services.
For example, you can use SOAP API to integrate Salesforce with your organization’s ERP and finance systems, deliver real-time sales and support information to company portals, and populate critical business systems with customer information.
Chatter API:
Chatter API is a REST API that provides programmatic access to Chatter feeds and social data such as users, groups, followers, and files.
It’s used by developers who want to integrate Chatter into a variety of applications such as mobile applications, intranet sites, and third-party Web applications. Chatter API is similar to APIs offered by other companies with feeds, such as Facebook and Twitter. Its advantages include ease of integration and development.
Bulk API:
Bulk API is based on REST principles and is optimized for loading or deleting large sets of data. You can use it to query, insert, update, upsert, or delete a large number of records asynchronously by submitting batches which are processed in the background by Salesforce.
SOAP API, in contrast, is optimized for real-time client applications that update small numbers of records at a time. Although SOAP API can also be used for processing large numbers of records, when the data sets contain hundreds of thousands of records, it becomes less practical. Bulk API is designed to make it simple to process data from a few thousand to millions of records.
The easiest way to use Bulk API is to enable it for processing records in Data Loader using CSV files. This avoids the need to write your own client application.
Metadata API:
Use Metadata API to retrieve, deploy, create, update, or delete customizations for your organization. The most common use is to migrate changes from a sandbox or testing organization to your production environment. Metadata API is intended for managing customizations and for building tools that can manage the metadata model, not the data itself.
The easiest way to access the functionality in Metadata API is to use the Force.com IDE or Force.com Migration Tool. These tools are built on top of Metadata API and use the standard Eclipse and Ant tools respectively to simplify the task of working with Metadata API.
Built on the Eclipse platform, the Force.com IDE provides a comfortable environment for programmers familiar with integrated development environments, allowing you to code, compile, test, and deploy all from within the IDE itself. The Force.com Migration
Tool is ideal if you want to use a script or a command-line utility for moving metadata between a local directory and a Salesforce organization.
Streaming API:
Use Streaming API to receive notifications for changes to data that match a SOQL query that you define.
Streaming API is useful when you want notifications to be pushed from the server to the client. Consider Streaming API for applications that poll frequently.
Applications that have constant polling action against the Salesforce infrastructure, consuming unnecessary API call and processing time, would benefit from this API which reduces the number of requests that return no data. Streaming API is also ideal for applications that require general notification of data changes.
This enables you to reduce the number of API calls and improve performance.
Apex REST API:
Use Apex REST API when you want to expose your Apex classes and methods so that external applications can access your code through REST architecture. Apex REST API supports both OAuth 2.0 and Session ID for authorization.
Apex SOAP API:
Use Apex SOAP API when you want to expose your Apex methods as SOAP Web service APIs so that external applications can access your code through SOAP. Apex SOAP API supports both OAuth 2.0 and Session ID for authorization.
What Is Visualforce View State? And What Are Best Practices To Reduce The View State Size?
Visualforce pages that contain a form component also contain an encrypted, hidden form field that encapsulates the view state of the page. This view state is automatically created, and as its name suggests, it holds the state of the page – state that includes the components, field values and controller state.
Best Practices to reduce the view state size:
Minimize number of form on a page. Use apex:actionRegion instead of using 2 or more forms.
Refine your SOQL to only retrieve the data needed by the page.
All public and private data members present in Standard, Custom and Controller extensions are saved.
Mark any Apex variables that are not necessary to the view state as Transient. (The transient variables are not passed to view state and therefore not stored in View State)
Create wizards with as few pages as possible
Use outputLink components instead of commandLink or commandButton components where possible as they don’t need to be nested in a form.
What Are Custom Settings?
Custom settings are similar to custom objects and enable application developers to create custom sets of data, as well as create and associate custom data for an organization, profile, or specific user.
All custom settings data is exposed in the application cache, which enables efficient access without the cost of repeated queries to the database. This data can then be used by formula fields, validation rules, Apex, and the SOAP API.
There are two types of custom settings:
List Custom Settings
A type of custom setting that provides a reusable set of static data that can be accessed across your organization. If you use a particular set of data frequently within your application, putting that data in a list custom setting streamlines access to it.
Data in list settings does not vary with profile or user, but is available organization-wide. Because the data is cached, access is low-cost and efficient: you don’t have to use SOQL queries that count against your governor limits.
Hierarchy Custom Settings
A type of custom setting that uses a built-in hierarchical logic that lets you “personalize” settings for specific profiles or users. The hierarchy logic checks the organization, profile, and user settings for the current user and returns the most specific, or “lowest,” value. In the hierarchy, settings for an organization are overridden by profile settings, which, in turn, are overridden by user settings.
What Is Apex?
It is the in-house technology of salesforce.com which is similar to Java programming with object oriented concepts and to write our own custom logic.
• Apex is a procedural scripting language in discrete and executed by the Force.com platform.
• It runs natively on the Salesforce servers, making it more powerful and faster than non-server code, such as JavaScript/AJAX.
• It uses syntax that looks like Java
• Apex can written in triggers that act like database stored procedures.
• Apex allows developers to attach business logic to the record save process.
• It has built-in support for unit test creation and execution.
Apex provides built-in support for common Force.com platform idioms, including:
• Data manipulation language (DML) calls, such as INSERT, UPDATE, and DELETE, that include built-in DmlException handling
• Inline Salesforce Object Query Language (SOQL) and Salesforce Object Search Language (SOSL) queries that return lists of sObject records
– Looping that allows for bulk processing of multiple records at a time
– Locking syntax that prevents record update conflicts
– Custom public Force.com API calls that can be built from stored Apex methods
– Warnings and errors issued when a user tries to edit or delete a custom object or field that is referenced by Apex
Note: Apex is included in Unlimited Edition, Developer Edition, Enterprise Edition, and Database.com
Apex vs. Java:
Commonalities
• Both have classes, inheritance, polymorphism, and other common OOP features.
• Both have the same name variable, expression, and looping syntax.
• Both have the same block and conditional statement syntax.
• Both use the same object, array, and comment notation.
• Both are compiled, strongly-typed, and transactional.
Apex vs. Java:
Differences
• Apex runs in a multi-tenant environment and is very controlled in its invocation and governor limits.
• To avoid confusion with case-insensitive SOQL queries, Apex is also case-insensitive.
• Apex is on-demand and is compiled and executed in cloud.
• Apex is not a general purpose programming language, but is instead a proprietary language used for specific business logic functions.
• Apex requires unit testing for development into a production environment.
Explain The Apex Data Manipulation Language (dml) Operations?
Use data manipulation language (DML) operations to insert, update, delete, and restore data in a database.
You can execute DML operations using two different forms:
Apex DML statements, such as:
insertSObject[]
Apex DML database methods, such as:
Database.SaveResult[] result = Database.Insert(SObject[])
While most DML operations are available in either form, some exist only in one form or the other.
The different DML operation forms enable different types of exception processing:
Use DML statements if you want any error that occurs during bulk DML processing to be thrown as an Apex exception that immediately interrupts control flow (by using try. . .catch blocks). This behavior is similar to the way exceptions are handled in most database procedural languages.
Use DML database methods if you want to allow partial success of a bulk DML operation—if a record fails, the remainder of the DML operation can still succeed. Your application can then inspect the rejected records and possibly retry the operation. When using this form, you can write code that never throws DML exception errors.
Instead, your code can use the appropriate results array to judge success or failure. Note that DML database methods also include a syntax that supports thrown exceptions, similar to DML statements.