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());
}
}