5

The scenario is:

  • I have an autonumeric field Perspective_Code__c.
  • I have a text field Original_AC_Code__c.
  • I have an external id text field Opportunity_Code__c.

When a record is inserted/updated, I need to calculate Opportunity_Code__c depending on: if Original_AC_Code__c has value, Opportunity_Code__c equals to Original_AC_Code__c else, Opportunity_Code__c equals to Perspective_Code__c.

I cannot use a formula field to calculate Opportunity_Code__c because is necessary have the field as external id.

I cannot use a before trigger because, on insert, I don't have Perspective_Code__c value.

I cannot use an after trigger because I need to update the same record being processed.

I cannot use a workflow because, on insert, Salesforce doesn't guarantee the Perspective_Code__c field has value when executing.

Someone can help me how/when I can use an autonumeric field to complete another text field?

Thanks!

1 Answer 1

5

With a little care you can use an after trigger.

Here is a contrived example (that just sets Account.Industry to 'xxx'):

public class MyClass {
    private static Boolean executing = false;
    public static void myLogic(Account[] accounts) {
        if (!executing) {
             executing = true;
             try {
                 Account[] updates = new Account[] {};
                 for (Account a : accounts) {
                     updates.add(new Account(id = a.Id, Industry = 'xxx'));
                 }
                 update updates;
             } finally {
                 executing = false;
             }
        }
    }
}

and the trigger:

trigger MyTrigger on Account (after insert, after update) {
    MyClass.myLogic(Trigger.new);
}

This works because:

  • it isn't the list of objects from the Trigger context that are updated (as updating these would result in the error "SObjectException: DML statment cannot operate on trigger.new or trigger.old") but rather a separate list with the same object ids
  • infinite recursion is avoided by using the static guard variable executing (that has to be in a separate class)

As all the required fields are available in the after trigger your logic would just be:

YourType__c[] updates = new YourType__c[] {};
for (YourType__c sob : sobs) {
    updates.add(new YourType__c(
            Id = sob.Id,
            Opportunity_Code__c = sob.Original_AC_Code__c != null
                    ? sob.Original_AC_Code__c
                    : sob.Perspective_Code__c
            ));
}
udpate updates;
1
  • Really clever. This workaround of have a new list of SObject to update in after trigger should be novel prize :) Apr 23, 2014 at 9:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .