I need to conditionally restrict the number of records that apex allows to be edited, based on user profile, number of records in the save transaction, and an oldmap newmap field compare. See attempt/questions below.
More information about the requirement
We allow users to perform mass DML on object__c
records using tools like Dataloader, but i need non admins to be subjected to a custom validation rule: "You may only edit field__c 1 record at a time per save transaction"
Attempted solution
trigger restrictCertainEditsToOneRecordMaximum on object__c (before insert, before update){
if(Trigger.size()>1){
for(Object__c object : (List<Object__c>)Trigger.new){
//only throw error when a non-admin user tries updating field__c more than once in a save transaction
if(object.field__c != Trigger.oldmap.get(object.Id).field__c && 'adminProfId_proofOfConcept'!=UserInfo.getProfileId();){
object.addError('You may only edit field__c 1 record at a time per save transaction');
}
}
}
}
Questions I think this would belong in a before update, before insert trigger on object__c. Does the community agree? Would the simplest implementation of this rule (keeping public read/write owd) be to check these 3 conditions in the before trigger? If all 3 are TRUE then call addError to display to users the required error mentioned above?
- trigger.new.size()>1
- compare oldmap newmap to see if the field__c was edited
- current users' profile not equal to system administrator