function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
JiriteachJiriteach 

Apex Trigger To Update Opportunity Owner ID Based On Picklist Value

Hi There,

I am attemping to write a simple Apex Trigger that updates the owner ID based on a picklist value.

Picklist contains the aliases of our account managers and based on this I want to update the owner ID on insert.

Reason for this is because we have administrators entering opportunities and it will save them time rather than having to create the record then change it owner.

I have the following:

trigger UpdateOwnerID on Opportunity (after insert) {
       
    for (Opportunity objOpportunity : Trigger.new)
    {
        if (objOpportunity.Owner.Alias <> objOpportunity.Account_Manager__c)               
        {
            objOpportunity.Owner.Alias = objOpportunity.Account_Manager__c;
        }
    }
   
   

}

But I keep getting this error:

Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger UpdateOwnerID caused an unexpected exception, contact your administrator: UpdateOwnerID: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.UpdateOwnerID: line 7, column 1

Any help would be appreciated.

Thanks
Best Answer chosen by Jiriteach
Phillip SouthernPhillip Southern
Hi, so you'll need to store users and alias before you reference them....best way to do it is by a Map and to bulkify...here is a revision to consider:

trigger UpdateOwnerID on Opportunity (before insert, before update) {
     Set<string> aliasscope = new Set<String>();
      for(opportunity opp : trigger.new)
      {
              aliasscope.add(opp.Account_Manager__c);
       }
    map<string,id> userIdbyAlias = new map<string,id>();  //Keep in mind this will only store one user id per alias
    for(User u : [Select id from user where Alias IN :aliasscope])
    {
            userIdbyAlias.put(u.Alias,u.Id);
     }
    for (Opportunity objOpportunity : Trigger.new)
    {
        if(userIdbyAlias.containskey(objOpportunity.Account_Manager__c)
        {

             if (objOpportunity.OwnerId <> userIdByAlias.get(objOpportunity.Account_Manager__c) )           
             {
                   objOpportunity.OwnerId = userIdByAlias.get(objOpportunity.Account_Manager__c);
              }
         }
    }

}

All Answers

Phillip SouthernPhillip Southern
Hi Jiriteach, so with triggers, keep in mind you are normally operating under the context and fields of the object associated to the trigger....in this case Opportunity.  In order to reference fields outside the opportunity object (like Owner.Alias) you will need to either create a formula field on the object to pull its value (so a formula field to display the value of owner.alias on the opportunity object) and use that formula field in the trigger or perform a SOQL query to pull the data when the trigger runs.

Also the second thing I notice is...when you perform the update statement...looks like its written to update to the alias field of the owner on the user table.....so if you are wanting to update the owner of the opportunity you can do

"objOpportunity.OwnerId"

To do that though, you need the Id of the user....not just the name...not sure what's being stored in that picklist.

JiriteachJiriteach
Hi There, 

Thanks for the pointers. 
So far I have the following and I think I am nearly there:

trigger UpdateOwnerID on Opportunity (before insert, before update) {
       
    User objUser = [select Id from User where User.Alias = Opportunity.Account_Manager__c limit 1];  
    for (Opportunity objOpportunity : Trigger.new)
    {
        if (objOpportunity.OwnerId <> objUser.Id)               
        {
            objOpportunity.OwnerId = objUser.Id;
        }
    }

}

I am getting an error being thrown though: Error: Compile Error: unexpected token: 'Opportunity.Account_Manager__c' at line 3 column 59

Any ideas?

Thanks

JiriteachJiriteach
So if I hardcode the select statement things work:

select Id from User where User.Alias = 'AJM' limit 1

BUT

I need this to be dynamic since I have a picklist called account manager. This stores aliases, like AJM above. So the question is how do I get a value from a picklist to add to my query?

User-added image

Thanks
Phillip SouthernPhillip Southern
Hi, so you'll need to store users and alias before you reference them....best way to do it is by a Map and to bulkify...here is a revision to consider:

trigger UpdateOwnerID on Opportunity (before insert, before update) {
     Set<string> aliasscope = new Set<String>();
      for(opportunity opp : trigger.new)
      {
              aliasscope.add(opp.Account_Manager__c);
       }
    map<string,id> userIdbyAlias = new map<string,id>();  //Keep in mind this will only store one user id per alias
    for(User u : [Select id from user where Alias IN :aliasscope])
    {
            userIdbyAlias.put(u.Alias,u.Id);
     }
    for (Opportunity objOpportunity : Trigger.new)
    {
        if(userIdbyAlias.containskey(objOpportunity.Account_Manager__c)
        {

             if (objOpportunity.OwnerId <> userIdByAlias.get(objOpportunity.Account_Manager__c) )           
             {
                   objOpportunity.OwnerId = userIdByAlias.get(objOpportunity.Account_Manager__c);
              }
         }
    }

}
This was selected as the best answer
JiriteachJiriteach
Thanks for the pointers. I've managed to get this working now.

Cheers
Maggie von SteinMaggie von Stein
Hi there,

I am a Salesforce Admin that could use some help and advice from a developer. When I took over the management of our SF platform there was a apex trigger written to auto assign the custom field IG Lead to a specific SF User based on the selected Industry Group. I found where to access this code in production however I am not sure how to make edits. One of the users that opportunities were being assigned to has left the company and I need to change out the name so that all default the IG Lead to the person that is now in that role. Posted code below. Any help and suggestions would be greatly appreciated. I am not familiar enough with how to make this minor update as I have access to our sandbox but have not done any development in there before. The name I need to change is from 'Ned Elton' to 'Dan O'Neil"

trigger OpportunityAssignIGOwner on Opportunity (before insert,before update) {
    Map<String,Id> UserNameIdMap = new Map<String,Id>();
    for(User objUser : [select id,name from User where name ='Eric Healy' or name='Ned Elton' or name='Shannon Hartley' or name='Grant McDougall']){
        UserNameIdMap.put(objUser.name,objUser.id);
    }
    
    System.debug('UserNameIdMap*****'+UserNameIdMap);
    
    
    for(Opportunity opp : Trigger.new){
        System.debug('Industry Group*****'+opp.IndustryGroup__c);
        if(opp.IndustryGroup__c =='CPR')
            opp.IG_Owner__c= UserNameIdMap.get('Eric Healy');
        if(opp.IndustryGroup__c =='FS')
            opp.IG_Owner__c= UserNameIdMap.get('Ned Elton');
        if(opp.IndustryGroup__c =='HC')
            opp.IG_Owner__c= UserNameIdMap.get('Shannon Hartley');
        if(opp.IndustryGroup__c =='TNT')
            opp.IG_Owner__c= UserNameIdMap.get('Grant McDougall');
        System.debug('IG_Owner__c*****'+opp.IG_Owner__c);
    }
}


Thank you,
Maggie