3

I have a field on case linked to an order that is present both in the case object and in the object order.

When the case field is true, the order field becomes true in a trigger (after insert or update). The case field cant be set to false after it has been set to true. I have written the following validation rule to do that: ISCHANGED(Field_c) && PRIORVALUE(Field__c) == true

But now I have to add this feature: when the field is set to true, another date field must be set to today date. Now my trigger is in after insert and upsert, therefore I cannot update the new case i am upserting.

I have 2 possible ways I believe: - modify the trigger leaving it in after mode and operating on the new case and updating the new case (is this acceptable?= - set the trigger in before mode but this way i would have to modify the validation rule cause it won't work anymore and i don't know how to fix it.

What do you suggest? Thanks

2 Answers 2

2

Although you cannot update trigger.new in the after context, you can still update the objects included in the trigger context variable. You just need to cache the values of trigger.new in a list. Then you can still update the values in that list.

Will give you an error as you cannot perform DML on trigger.new

trigger AccountTrigger on Account (after update) {

     for(Account a : trigger.new){
        a.Name = 'New Name';
     }
     update trigger.new;
}

Will not give an error as you are updating a list of Accounts, not trigger.new

trigger AccountTrigger on Account (after update) {

         list<Account> accounts2Update = new list<Account>();
         for(Account a : trigger.new){
            accounts2Update.add(new Account(
                 Id = a.Id,
                 Name = 'New Name'
            ));
         }
         update accounts2Update;
}
2
  • 2
    Note that the query is not necessary to do the update: you can create new Account objects setting their IDs to the keys of Trigger.newMap.
    – Keith C
    Jul 18, 2014 at 13:27
  • Very good point. Didn't even think to avoid the SOQL. Updated the answer to reflect. Jul 18, 2014 at 17:13
1

But now I have to add this feature: when the field is set to true, another date field must be set to today date. Now my trigger is in after insert and upsert, therefore I cannot update the new case i am upserting.

I think the simplest solution would be to use workflow based on ISCHANGED(Field_c) && PRIORVALUE(Field__c) == true. When this validation rule is triggered for the first time, you also want to set the other date field you mention to a value of today().

2
  • But I'd have to write a workflow rule for that, right?
    – tony danza
    Jul 18, 2014 at 14:43
  • Yes, that you would. Should be fairly straightforward to do and much easier to maintain than a trigger.
    – crmprogdev
    Jul 18, 2014 at 15:19

You must log in to answer this question.

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