Mixing Workflow Rules and Triggers

I like to use the declarative side of Salesforce as often as possible, but sometimes I run into limitations with workflow rules and I end up turning to code. One thing I can’t do in workflow rules is create new records. Let’s say I have a requirement that says when certain scenarios are met I want to create a child record. I could write the entire thing in a trigger, but I want to make it easy to modify my logic later on if business requirements change. (I know from experience that they do change often.) What I want to do is allow the entry logic to be easily maintained and use my trigger to only do the DML. Here’s my solution for a fictitious requirement to create a new opportunity for an account when the a field called Upsell Opportunity gets change to “Yes” on an Account.

1. Create a new boolean field on Account. Let’s call it “Run Trigger”.

2. Create a workflow rule that sets the Run Trigger field to true when the Upsell Opportunity field equals “Yes”.

workflow rule definition

3. Create a trigger that fires when the Run Trigger field is true that creates a new Opportunity. The trigger also sets the run trigger flag to false so it won’t run again.

trigger createUpsellOppTrigger on Account (before update) {
    Opportunity[] oList = new Opportunity[]{};
    for(Account a : Trigger.new){
        if (a.RunTrigger__c) {
            oList.add(new Opportunity(AccountId = a.id,
                     Name = 'Upsell Opp',
                     CloseDate = Date.today().addDays(7)));
            a.RunTrigger__c = false;
    if (!oList.isEmpty())
        insert oList;

Now when the business requirements change, I can just update my workflow rule. For example, if we now want an opportunity to be created when the Upsell Opportunity is Yes or Maybe, I’d change my workflow rule like so:¬†Account: Upsell Opportunity EQUALS Yes,Maybe. I don’t have to go and update my code and I can react faster to business changes.