8

I have noticed the strange behaviour of salesforce due to which even my code broke down in production.

I was trying to stop the user from updating some field..I used before udpate trigger and code like Trigger.new[i].LastModifiedbyId..

Ideally it should give the current user in Trigger.new[i].LastModifiedbyId in but it gives oldrecordLastModifiedbyId..

Although userinfo.getuserid resolves the problem later.

Any idea about this behaviour of salesforce.

  • I feel like this post should be protected :) – highfive May 6 '16 at 7:32
  • 1
    @highfive They're really to prevent a bunch of first time posters adding "Thanks!" If we see a bunch of those pop up, we'll protect it! – Adrian Larson May 6 '16 at 23:05
  • Oh ok, got the idea – highfive May 7 '16 at 20:45
13

System audit fields like LastModifiedById, LastModifiedDate, and SystemModStamp are not updated until later in the transaction. You shouldn't rely on any of those values being set, especially in a "before" trigger; even OwnerId might have the wrong value during a trigger, especially if assignment rules are going to be evaluated. Using UserInfo.getUserId() is the most accurate way to determine the current user modifying a record.

Edit: The fields LastModifiedById and LastModifiedDate, at least, appear to be set during step 6 (temporary save to database) in the Triggers and Order of Execution document. This means that an after trigger should, in theory, be able to perform the validations you're looking. Validation rules and before triggers are executed before this temporary record save, and will definitely see the wrong values.

  • 1
    So where does it get set in the Order of Execution? – Adrian Larson May 6 '16 at 19:25
  • @AdrianLarson Thanks for pointing that out. I went ahead and tracked it down by empirical evidence. Since it's not clearly documented, however, I guess it could change at any time... – sfdcfox May 6 '16 at 23:00

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.