0

I have created a before updated trigger and I am trying to update the title of the user. After saving the record, the title does not get populated although when I debug the value it actually hold it. Below is the code : newUserList is Trigger.new and the below logic is called from before update trigger.

public static void updateUserTitlePrefix(List<User> newUserList){
     for(User userRecord : [SELECT Id, Name, TitleFROM User WHERE Id IN:newUserList]) {
            if(userRecord.Title != null) {
                userRecord.Title = 'ABC ' + userRecord.Title;
                System.debug('userRecord.Title1 ::'+ userRecord.Title);
            } else {
                userRecord.Title = 'ABC ';
                System.debug('userRecord.Title2 ::'+ userRecord.Title);
            }
      }
}

When I checked the logs userRecord.Title actually holds the correct value. Not sure what am I missing.

2
  • You don't need to query the records. Just update the users inside your newUserList. – Martin Lezer May 5 at 16:18
  • @MartinLezer Thank you it worked. But can you tell me how does it make a difference if I query and then update ? – sfdcLearner May 5 at 16:22
2

First, you dont need to query records in before Update.

public static void updateUserTitlePrefix(List<User> newUserList){
    for(User userRecord : newUserList) {
        if(userRecord.Title != null) {
            userRecord.Title = 'ABC ' + userRecord.Title;
        } else {
            userRecord.Title = 'ABC ';
        }
    }
}

Also this code should work. Either something might be there in the workflow to set it back to original value, or your record might be failing to be updated. Also check if there is any after update logic or async logic which resets the title value.

Can you check the debug log for the transaction.

UPDATE I see the above code already worked for you, let me try to explain why it was not working with query.

newUserList will hold value loaded from Database, now when you again query the data, it holds a new instance of the data, which you change in your loop, but the same never goes in DB as there is not commit happening for that data.

newUserList you should always loop and change this so that the changed value is committed at the end of transaction.

0

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.