Professional Documents
Culture Documents
Apex Flow Control - Preventing Infinite Loops: 1. What Are Recursive Triggers? How Can We Avoid The Recursion Problem?
Apex Flow Control - Preventing Infinite Loops: 1. What Are Recursive Triggers? How Can We Avoid The Recursion Problem?
1. What are recursive triggers? How can we avoid the recursion problem?
When this happens you will undoubtedly run into one very specific problem. You have a piece of code A that causes code B to
execute which then causes code A to execute which then causes code B to execute. OH NO! Infinite loop, governor limits AHHHHH!
Fear not! For there is a very simple solution to this problem. The extremely clear and concise diagram below shows a common
scenario.
Let’s say we have an update trigger that sends a group of objects to be processed by an @future asynchronous method. There is a
good chance this method will need to update the records. This would normally cause the trigger to execute and the @future method
to be called again, hence our unstoppable loop. So how do we stop this loop? Before we perform the update on the records we need
to say, “Hey, this is a update from a @future methods, don’t do anything”. We can do this by creating a simple Boolean value in a
utility class and can be accessed by anycode in context of the update operation.
Below is the code of how something like this would work. First let’s look at the very simple solution. Yup, this is it. Some minor
changes to our @future and trigger code and this is it.
public class utility{
public static boolean isFutureUpdate;
}
Here is the trigger, we only want the code in this trigger to execute if the isFutureUpdate variable is not true.
trigger updateSomething on Account (after insert, after update) {
/*We only want this trigger to perform it's logic when the
update is not from an @future method */
if(utility.isFutureUpdate == null || utility.isFutureUpdate == false){
Set<Id> idsToProcess = new Se<Id>();
for(Account acct : trigger.new){
if(acct.NumberOfEmployees > 500){
idsToProcess.add(acct.Id);
}
}
//Send Ids to @future method for processing
futureMethods.processLargeAccounts(idsToProcess);
}
}
And here is our @future method. The only thing we need to add is one line of code to set the isFutureUpdate variable to true before
we perform the update.
public class futureMethods{
@future
public static void processLargeAccounts(Set<Id> acctIDs){
List<Account> acctsToUpdate = new List<Account>();
/* Do awesome stuff with apex code */
/*Before we perform this update we want to set the
isFutureUpdate boolean in our utility class to true */
utility.isFutureUpdate = true;
/*Now we can perform the update. The trigger will still
fire but none of the code inside of it will execute and
this method will not be called again*/
update acctsToUpdate;
}
}
Now when the trigger is fired the @future method will not be called again.
This example shows the interaction between asynchronous operations but you can use this same solution if you have triggers that
update triggers and cause a loop.
Because Apex runs in a multitenant environment, the Apex runtime engine strictly enforces a number of limits to ensure that runaway Apex does not
monopolize shared resources. Theselimits, or governors, track and enforce the statistics outlined in the following table. If some Apex code ever
exceeds a limit, the associated governor issues a runtime exception that cannot be handled.
Governor limits apply to an entire organization, as well as to specific namespaces. For example, if you install a managed package created by
a salesforce.com ISV Partner fromForce.com AppExchange, the components in the package belong to a namespace unique from other components in
your organization. Consequently, any Apex code in that package can issue up to 20 DML statements while executing. In addition, any Apex code that
is native to your organization can also issue up to 150 DML statements, meaning more than 150 DML statements might execute during a single
request if code from the managed package and your native organization both execute. Conversely, if you install a package from AppExchange that is
not created by a salesforce.com ISV Partner, the code from that package does not have its own separate governor limit count. Any resources it uses
counts against the total for your organization. Cumulative resource messages and warning emails are also generated based on managed package
namespaces as well. For more information on salesforce.com ISV Partner packages, see salesforce.com Partner Programs.
Description Limit
or database.emptyRecycleBin
Total stack depth for any Apex invocation that recursively fires triggers due to insert, update, 16
or delete statements4
Maximum timeout for all callouts (HTTP requests or Web services calls) in a request 120 seconds
Default timeout of callouts (HTTP requests or Web services calls) in a request 10 seconds
Maximum size of callout request or response (HTTP request or Web services call) 6 3 MB
1
In a SOQL query with parent-child relationship sub-queries, each parent-child relationship counts as an additional query. These types of queries have
a limit of three times the number for top-level queries. The row counts from these relationship queries contribute to the row counts of the overall script
execution.
2
Calls to the following methods count against the number of DML statements issued in a request:
Approval.process
database.emptyRecycleBin
delete and database.delete
findSimilar
insert and database.insert
merge
rollback
runAs
setSavePoint
update and database.update
upsert and database.upsert
3
Batch Apex heap size is 6 MB. Email services heap size is 18 MB.
4
Recursive Apex that does not fire any triggers with insert, update, or delete statements exists in a single invocation, with a single stack.
Conversely, recursive Apex that fires a trigger spawns the trigger in a new Apex invocation, separate from the invocation of the code that caused it to
fire. Because spawning a new invocation of Apex is a more expensive operation than a recursive call in a single invocation, there are tighter restrictions
on the stack depth of these types of recursive calls.
5
Salesforce also imposes a limit on the number of future annotations: 200 method calls per full Salesforce user license per 24 hours. This is an
organization-wide limit. For example, suppose your organization has five full Salesforce user licenses and 100 Customer Portal User licenses. Your
entire organization is limited to only 1,000 method calls every 24 hours (5 * 200, not 105.)
The HTTP request and response sizes are calculated as part of the total heap size. So regardless of this limit, don't exceed the 3 MB total heap size.
7
Describes include the following methods and objects:
ChildRelationship objects
RecordTypeInfo objects
PicklistEntry objects
fields calls
Use the Limits methods to determine the script execution limits for your code while it is running. For example, you can use
the getDMLStatements method to determine the number of DML statements that have already been called by your program, or
the getLimitDMLStatements method to determine the total number of DML statements available to your code in that context.
For more efficient SOQL queries, particularly for queries inside of triggers, use selective (indexed) queries. Selective queries filter on primary keys,
foreign keys, names, audit dates (such asLastModifiedDate), or External ID fields. In large organizations, non-selective queries could be stopped
at runtime in order to prevent very long running operation times. If you need them for your application, contact your salesforce.com representative.Note
If you use a non-selective query in a trigger against an object that contains more than 100000 records an error is generated. You should
include indexed fields in the WHEREclause to avoid these exceptions.
Static variable values are reset between API batches, but governor limits are not. Do not use static variables to track state information
on API batches, because Salesforce may break up a batch into smaller chunks than the batch size you specify.
In addition to the execution governor limits, Apex has the following limits:
marked AppExchange Certified). The code in those types of packages belong to a namespace unique from the code in your
This limit also does not apply to any code included in a class defined with the @isTest annotation.
If a SOQL query runs more than 120 seconds, the request can be canceled by Salesforce.
The maximum number of records that an event report returns for a user who is not a system administrator is 20,000, for system
administrators, 100,000.
Each organization is allowed 10 synchronous concurrent events, each not lasting longer than 5 seconds. If additional requests are made
A user can have up to five query cursors open at a time. For example, if five cursors are open and a client application still logged in as the
same user attempts to open a new one, the oldest of the five cursors is released.
Cursor limits for different Force.com features are tracked separately. For example, you can have five Apex query cursors, five batch cursors,
In a single transaction, you can only reference 10 unique namespaces. For example, suppose you have an object that executes a class in a
managed package when the object is updated. Then that class updates a second object, which in turn executes a different class in a different
package. Even though the second package wasn't accessed directly by the first, because it occurs in the same transaction, it's included in the
Salesforce limits the total number of messages that all email services combined, including On-Demand Email-to-Case, can process daily.
Messages that exceed this limit are bounced, discarded, or queued for processing the next day, depending on how you configure the failure
response settings for each email service. Salesforce calculates the limit by multiplying the number of user licenses by 1,000. For example, if
you have ten licenses, your organization can process up to 10,000 email messages a day.
Email service addresses that you create in your sandbox cannot be copied to your production organization.
For each email service, you can tell Salesforce to send error email messages to a specified address instead of the sender's email address.
Email services rejects email messages and notifies the sender if the email (combined body text, body HTML and attachments) exceeds
A. For those that don’t have time to weed through all 171 pages of the Spring ‘10 Release Notes, I’ve pulled out a few of my favorites for your viewing
pleasure. I didn’t hit all of the items in the release notes so make sure you pull up the the PDF and check out the goodies in detail.
SOQL Enhancements
Date Functions
A slew of new date functions for SOQL to make your life easier.
Visualforce Enhancements
Force.com IDE
The Force.com IDE Spring ‘10 release is scheduled for February 15th. Not sure of the new features but from what I have heard in the past you should
(safe harbor) be able to copy from from SOQL search results.
New UI Theme
The new UI theme that was unveiled at DF09 is an org-wide update. The new UI supports IE 7 & 8, Firefox 3.0.x and Safari 3.2.x. Sorry Chrome!
Dashboard Enhancements
With custom dashboard tables you can create tables with up to four columns, with column totals for number and currency summary fields.
With dashboard finder, you can quickly find a dashboard by typing its name in the search filter. All accessible dashboards matching that text
are dynamically displayed in the drop-down list.
New visibility option for report and dashboard folders to deny access to a folder for portal users (“This folder is accessible by all users,
except for portal users”).
Globalization Enhancements
A. Scenario: I want to pass values back to a Visualforce controller without having to resort to hidden input fields and using the {!
$Component.<<fieldid>>} notation because that's only evaluated when the page is generated and so doesn't lend itself well to dynamic
setups.
The problem: All of the solutions I was able to find involved using an apex:actionFunction with nested apex:paramtags (e.g.
see here and here), which is fine except that whenever I tried this the generated javascript function never had any parameters,
i.e. doStuff() {...}
Solution: You must specify a rerender attribute in the apex:actionFunction tag! Without this the generated function does take any
parameters, but as soon as you put it in then it does - even if you just leave it empty, i.e. the below code will generate doStuff(x)
{...} Go figure :)
A. A timer that sends an AJAX update request to the server according to a time interval that you specify. The update request can then result in a full or
partial page update. You should avoid using this component with enhanced lists.
Note that if an <apex:actionPoller> is ever re-rendered as the result of another action, it resets itself. An <apex:actionPoller> must be
within the region it acts upon.
Ans :
Master Detail
Many to Many
Lookup
Hierarchical
6. 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, which should have autonumber as unique identification and create two master
relationships for both objects, no need create tab for this object. Now on both object, add this field as related list.
7. If one object in Salesforce have 2 triggers which runs “before insert”. Is there any way to control the sequence of
execution of these triggers?
Ans : Salesforce.com has documented that trigger sequence cannot be predefined. As a best practice create one
trigger per object and use comment blocks to separate different logic blocks. By having all logic in one trigger you
may also be able to optimize on your SOQL queries.
Ans : As per now, salesforce does not allow to delete any user, however you can deactivate the user.
9. How to delete the users data from Salesforce?
Ans : To delete the Users Data go to Setup | Administration Setup | Data Management | Mass Delete Record, from
there select the objects like Account, Lead etc and in criteria select the users name and delete all records of that user
related to particular object.
10. How to restrict the user to see any record, lets say opportunity?
Ans : set up opportunity sharing to be private. If both users are admins or have view all records on opportunity, then
that overrides private sharing.
11. What is the difference between trigger.new and trigger.old in Apex – SFDC?
Ans :
Trigger.new :
Returns a list of the new versions of the sObject records. Note that this sObject list is only available in insert and
update triggers, and the records can only be modified in before triggers.
Trigger.old :
Returns a list of the old versions of the sObject records. Note that this sObject list is only available in update and
delete triggers.
1. What is Apex ?
Ans: It is the in-house technology of salesforce.com which is similar to Java programming with object oriented
concepts and to write our own custom logic.
2. What is an S-Control ?
Ans: S-Controls are the predominant salesforce.com widgets which are completely based on Javascript. These are
hosted by salesforce but executed at client side. S-Controls are superseded by Visualforce now.
3. What is a Visualforce Page ?
Ans: As I said in the above answer, S-controls are superseded by Visulaforce, 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.
4. Will Visual force still supports the mege fields usage like S-control?
Ans: Yes. Just like S-Controls, Visualforce Pages support embedded merge fields, like the {!$User.FirstName} used
in the example.
Text
HTML with Letter Head
Custom HTML
Visual force
ISNULL:
Determines if an expression is null (blank) and returns TRUE if it is. If it contains a value, this function returns
FALSE. Text fields are never null, so using this function with a text field always returns false. For example, the
formula field IF(ISNULL(new__c) 1, 0) is always zero regardless of the value in the New field. For text fields, use
the ISBLANK function instead.
Multi-select picklist fields are never null in s-controls, buttons, and email templates, so using this function with a
multi-select picklist field in those contexts always returns false.
Empty date and date/time fields always return true when referenced in ISNULL functions.
Choose Treat blank fields as blanks for your formula when referencing a number, percent, or currency field in an
ISNULL function. Choosing Treat blank fields as zeroes gives blank fields the value of zero so none of them will be
null.
Merge fields can be handled as blanks, which can affect the results of components like s-controls because they can
call this function.
When using a validation rule to ensure that a number field contains a specific value, use the ISNULL function to
include fields that do not contain any value. For example, to validate that a custom field contains a value of ’1,’ use
the following validation rule to display an error if the field is blank or any other number: OR(ISNULL(field__c),
field__c<>1)
ISBLANK:
Determines if an expression has a value and returns TRUE if it does not. If it contains a value, this function returns
FALSE.
Use ISBLANK instead of ISNULL in new formulas. ISBLANK has the same functionality as ISNULL, but also
supports text fields. Salesforce.com will continue to support ISNULL, so you do not need to change any existing
formulas.
A field is not empty if it contains a character, blank space, or zero. For example, a field that contains a space
inserted with the spacebar is not empty.
Use the BLANKVALUE function to return a specified string if the field does not have a value; use the ISBLANK
function if you only want to check if the field has a value.
If you use this function with a numeric field, the function only returns TRUE if the field has no value and is not
configured to treat blank fields as zeroes.
You can add, edit, or delete Apex using the Salesforce.com user interface only in a Developer Edition organization,
a Salesforce.com Enterprise Edition trial organization, or sandboxorganization. In a Salesforce.com production
organization, you can only make changes to Apex by using the Metadata API , deploy call, the Force.com IDE, or
theForce.com Migration Tool. The Force.com IDE and Force.com Migration Tool are free resources provided by
salesforce.com to support its users and partners, but are not considered part of our Services for purposes of the
salesforce.com Master Subscription Agreement.
1. What are recursive triggers. How can we avoid the recursion problem?
2. What are Apex Governer Limits.?
3. What are the Spring’10 features?
4. How do you use an actionFunction tag?
5. What is the difference between apex:actionFunction and apex:actionSupport tag?
6. What is actionPoller?
7. How do you do FileUpload using Visualforce?
8. What is the difference between a Profile and Role?
9. What is appexchange? How can I host my application on appexchange?
10. What are the different editions available on salesforce?
11. What is batch apex. ?
12. When will we use batch apex and what is the best practice?
13. What are webservice callouts?
14. What are wrapper classes?
15. When do we use wrapper classes?
3.
4. What is the difference between Lookup Relationship and Master-Detail Relationship?
5. True or False? If you were to delete a record that had a lookup to a child object, all child object records
would get deleted as well.
6. Where is the view Account hierarchy link?
7. What does the Account Hierarchy tell or do?
8. Where can you make a field required?
9. I'm setting up different page layouts for different user profiles. As a system administrator, is there another
way to see what the user sees instead of them granting log in access to you?
10. What type of Workflow Alerts are there?
11. Validation Rules, What are they use for in Salesforce?
12. What is Data loader?
13. What is the difference between Profiles and Roles in Salesforce.com?
14.