0

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
1

It is possible that other users may update other fields along with field__c so you need to check that other fields are not changed in if condition. So your algorithm should be something like

  • trigger.new.size()>1

  • compare oldmap newmap to see if the field__c was edited and compare oldmap newmap to see other than field__c fields are not updated.

  • current users' profile not equal to system administrator

  • i actually want the addError to occur anytime that field__c is edited in a batch size of 2 or more, therefore i think comparing oldmap and newmap for field__c is sufficient for my needs. – Peter Noges Sep 24 '17 at 19:09
  • You have written you may only edit field__c so I thought you don't want to update other fields.. if it is not like that then your algo looks correct.. – Amit Sep 24 '17 at 19:21

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.