2

So let's say I have an sObject User:

Standard Fields

TimeZoneSidKey

Custom Fields

Time_Zone__c

When a user updates TimeZoneSidKey I want to automatically update the custom field Time_Zone__c for them using a trigger.

So far this is a sample of the code I have. The problem I have is that. When I update "userInfo" it makes this trigger run again, and this happens recursively and infinitely until the computer runs out of stack space. What would be the best way to design something like this? My idea was to maybe instead of doing "update" userInfo I would save the user sObject, delete it, and re-insert it. However, I'm not sure if that is even possible and even if so it simply shifts the problem onto the delete and insert triggers.

trigger updateTimezoneSetting on User (before update) {

    for (User u : Trigger.new) {
        // found the user who triggered this event.
        if( UserInfo.getUserId() == u.Id ) {

            // When a user changes their locale setting, update their timzone
            User userInfo = [SELECT Time_Zone__c, TimeZoneSidKey FROM User WHERE Id = :u.Id];

            if( userInfo.TimeZoneSidKey == 'America/Chicago' ){
                userInfo.Time_Zone__c = 'CST';
            }

        // Update the user object
        try {
            update userInfo;
        } catch (DmlException e) {
           // The timezone wasn't updated successfully.
           u.addError(e.getMessage());
        }
    }
  • 1
    Updates in a Before trigger don't need an explicit update. When using an update in an after trigger, use a static variable to prevent recursion. – techtrekker Jun 28 '13 at 20:24
1

All changes made to an SObject on a Before trigger are saved on execution finish, provided no unhandled exceptions were thrown.

So, you don't have to recover the User SObject again. Just update it's values using the Trigger.new reference and it will be updated automatically:

trigger updateTimezoneSetting on User (before update) {
  for (User u : Trigger.new) {
      // found the user who triggered this event.
      if( UserInfo.getUserId() == u.Id ) {
          if( u.TimeZoneSidKey == 'America/Chicago' ){
              u.Time_Zone__c = 'CST';
          }
  }
  • So basically, I'm editing the fields before they're saved and then after this trigger is finished running the object just finished updating itself? – EthanLWillis Jun 28 '13 at 19:45
  • Exactly that! :) – André Medeiros Jun 28 '13 at 20:16
  • I would also recommend adding a return; statement inside your inner if clause so that you don't end up checking for every user Id every time the trigger runs, even after you found the record you're looking for. – André Medeiros Jun 28 '13 at 20:18
  • Glad I could help! :) – André Medeiros Jun 28 '13 at 21:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.