0

I have an odd problem. I have a trigger to update opportunity owner if custom field value changes. As I am updating an owner field by selecting random user, sometime it is also possible that owner won't transfer to new user due to user is not have access. Can i display a popoup message via trigger that field has not been updated?

trigger UpdateOwner on Opportunity (before insert, before update) {
  for(Opportunity opp : Trigger.new){
        if(Opp.Owner__c!=null && Opp.Owner__c != trigger.oldMap.get(Opp.Id).Owner__c){
            Opp.ownerid = opp.Owner__c;
        }
    }
}
1

Before triggers, when executed in the context of the user interface will be all-or-nothing. If the trigger fails a validation rule or other SFDC-imposed requirement, the trigger will fail and all updates rolled back. The user will see an error at the top of the screen that identifies the failure

If you have multiple triggers on the same object and one fails, they all fail.

I am updating an owner field by selecting random user,

This is of course going to lead to issues if you don't filter the available users to assign for validity to prevent errors. If you want a custom error message , use the following:

trigger UpdateOwner on Opportunity (before insert, before update) {
  for(Opportunity opp : Trigger.new){
        if(Opp.Owner__c!=null && Opp.Owner__c != trigger.oldMap.get(Opp.Id).Owner__c){
            if (isValidAssignee(opp.Owner__c)) {
              Opp.ownerid = opp.Owner__c;
            else {
              opp.addError('Unable to change owner because ...');
            }
        }
    }
}

where isValidAssignee is some method you write that returns a Boolean. Most likely, you will beed to bulk query the User record for all the opp.Owner__c in the batch as these values aren't implicitly in the trigger context.

0

your trigger can flag a record as having an error try{ if(Opp.Owner__c!=null && Opp.Owner__c != trigger.oldMap.get(Opp.Id).Owner__c){ Opp.ownerid = opp.Owner__c; } } catch(exception ex) {opp.addError('Your custom error message'); }

this can show a custom error message

  • this will only work if opp.Owner__c is not of type Id. If owner__c represents, say, an inactive user, the failure will occur after the trigger has finished as this is a before trigger – cropredy Sep 6 at 14:49

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.