2

I have a scheduled apex job which updates a field which is controlled by a validation rule as follows:

AND(
    Not(ISNEW()), 
    $Profile.Name != "System Administrator",
    ISCHANGED(theFieldInQuestion)
)

This validation rule prevents anyone from changing the value in theFieldInQuestion UNLESS that person is a System Administrator.

The scheduler runs as system, according to the documentation located here:

https://help.salesforce.com/articleView?id=code_schedule_batch_apex.htm&type=0

My question is : What can I add to this AND clause in the validation rule which would allow the Scheduled Apex Job to update theFieldInQuestion ?

  • In the Scheduled Jobs list, what is the profile of the User shown as having Submitted the job? – Thomas Taylor May 2 '19 at 12:55
8

Scheduled Apex runs in system mode, but that's not the same as running with a context user that is a system administrator. In system mode, FLS and CRUD aren't enforced against you (you control the enforcement of Record-Level security via [with|without|inherited] sharing declarations), and Apex class permissions are ignored.

Every Scheduled Apex job has a context user, which is the user who scheduled the job. Each time the job is executed, it remains in the context of that user and their profile and role. If the Scheduled Apex job is scheduled by, for example, a Standard User, it will run in system mode, but under the rubric of that user. UserInfo.getUserId() will return their Id, and any and all formula-type references to User fields will refer to them.

Easy fixes:

  • Schedule the class by doing Login As the desired System Administrator
  • Change the validation rule to vet changes by looking at a Custom Permission with $Permission.some_permission_name, and assign that Custom Permission to allowed users via a Permission Set.
| improve this answer | |

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.