Showing posts with label trigger. Show all posts
Showing posts with label trigger. Show all posts

Saturday, October 31, 2015

Field Update + Update Records + Apex Trigger = ?

While the "Triggers and Order of Execution" page in the Winter '16 Force.com Apex Code Developer's Guide gives good information about the high-level order of operations, developers reading it are still unclear about how complex interactions unfold across objects that use workflow rules, Apex triggers, and Process Builder ("PB") processes.

Let's take a relatively simple set of automation applied to a single object:

  • A workflow rule with a field update
  • A recursion-enabled process that updates the record which starts the process
  • An Apex trigger

When a transaction is processed, how many times do each of the above automation components execute in that single transaction? The answers below may surprise you/

Component TypeNum Executions
Workflow Rule1
Process6
Trigger8

The exact step order in which the components were executed is illustrated below.

Workflow RuleProcessTrigger
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

The takeaway should be that developers ought to be very careful when adding automation to an environment that uses "all of the above", meaning workflow rules, processes, and triggers.

Saturday, April 25, 2015

Recursive Process with Autolaunched Flow

In the old days of Salesforce, if a workflow field update occurred during a DML operation, the before and after triggers would for that object would execute a second time. But in the new world of Process Builder with autolaunched flows, how does the order of operations play out?

The Spring '15 documentation seems to imply that processes only fire once. The reason I say this is there is no corresponding explanation for processes in the same vein as the explicit explanation (shown below) for how a workflow rule can cause triggers to fire again.


As with many things in Salesforce, I like to trust and verify. And I found that Process Builder processes actually can cause triggers and the process itself to execute up to five (5) more times. I couldn't find this documented anywhere, but that seems to be the de facto limit on process recursion.

The proof


To prove this to myself, I decided to stage a manual test based on the following constructs:
  • A custom object named TriggerEvent__c exists as a child to the Account object
  • An Account trigger exists to create a TriggerEvent__c record before update
  • A process exists that launches a flow, which increments the Num Employees value by one if Num Employees is not blank

Under this setup, when I updated an account and entered 100 for Num Employees, I actually ended up with 106 for Num Employees and six new child TriggerEvent__c records.

update vs. undelete in Apex Triggers

Based on the Implementing Triggers training module, there are only four DML operations for which triggers can be executed: insert, update, delete and undelete. But, when an undelete operation occurs, does that also count as an update operation, whereby the sObject.IsDeleted value is toggled?

To settle the matter for my own benefit, I create an Apex test to validate my assumptions. What I learned and confirmed were the following:

  • Only one of Trigger.isUpdate, Trigger.isDelete and Trigger.isUndelete will ever be true during trigger execution. This means that the three operations are indeed distinct and constitute different trigger contexts.
  • The ALL ROWS keyword is required to retrieve soft-deleted records that are in the Recycle Bin

Below are the trigger and its test class I used.

AccountTrigger.cls



AccountTriggerTest.cls


Friday, August 8, 2014

Created By and Last Modified By not set before insert or update

After some frustrating troubleshooting of what I thought would be simple code today, I learned something unexpected: Created By and Last Modified By are not populated or set in the before context of DML operations. This means that before insert, CreatedById, CreatedDate, LastModifiedById and LastModifiedDate are all empty. And before update, LastModifiedById and LastModifiedDate will reflect the previous person to modify the record, not the current user (which would be yourself if you are the one editing the record).

While this was counter-intuitive at first, I came to realize that there's no need to rely on those fields in the context of Apex triggers. All I really need is UserInfo.getUserId() and DateTime.now() to get the time.

Just like that... I learned something new today.

Monday, May 26, 2014

Last Event or Task Date vs. Last Activity Date

Salesforce gives users the ability to run reports on the Last Activity Date for all objects, out of the box. But what if users wanted to distinguish between Last Event Date vs. Last Task Date? Or break up the data by other criteria?

Luckily, the Declarative Rollups for Lookups package (thanks to Andy Fawcett) can solve this problem, with only a few minor tweaks to work around a Salesforce limitation: field ActivityDate does not support aggregate operator MAX.

The general idea is to create two custom fields on the object of your choice: Last Event Date and Last Task Date. Follow these up with two Lookup Rollup Summaries, and you can now easily split your activity data by Tasks vs. Events. The end result? Reports like the following.


Follow this tutorial and give these new fields a try! Please add a comment below to let me know whether this tip works for you.

Friday, October 4, 2013

Force.com #Tested, Standard Pattern for Apex Unit Tests

The first step to writing an Apex unit test is... just to lay down the framework. The boring stuff, really. Declare the class, add the isTest annotation, declare a testMethod-qualified method, etc. And to make boring matters worse, in practice Apex unit testing is pretty important to get right.

The reason is simple: In addition to deploying your own customizations, Salesforce will upgrade your org 3 times a year with 100+ new features per release. Whether you like it or not. Assuming CRM is fairly important to your organization, who's going to run tests for your org every time a new release happens, to make sure the business can continue to operate?

  • Code coverage and test methods are intended to make sure that customizations work correctly, release after release, with minimal human effort
  • Good tests help to make sure your code works not only for one-off record edits but also for batch inserts, updates and deletes
  • With good intent, Salesforce requires you to have at least 75% code coverage to deploy new code. So, if you have to write tests anyway, let's just do it right the first time. Build the tests to add value as regression tests, instead of just time drains.


Understanding the significance of these tests, a new developer may find writing good tests to be quite daunting, second-guessing himself and worrying about whether he followed best practices. Then, in frustration, he could decide to just "screw it" and hack something out to achieve the minimum amount of code coverage required to just push a risky feature into production. Bad outcome.

To help a developer avoid this sub-optimal decision, he can adopt a standard test class structure that is easily adapted for all Apex unit tests. Below is one such self-documenting template for Apex unit tests, using a contrived example of trying to roll-up all activities related to a particular contact record.


There are lots of comments and little code in the above block, which is intentional to leave material for the rest of this series. :-) Subsequent posts will dive into each step above in more detail, walking through sample implementations by building out this example trigger test class.

But regardless of whether you're testing triggers, controllers, extensions, Schedulables or anything else in Apex, the general steps above should remain the same for your test methods. This way, Apex unit tests transform from time-and-materials liabilities in a Salesforce org to valuable assets that shine every time anyone goes to release a new feature.