Find your content:

Search form

You are here

Trigger to update a picklist field from another picklist field

 
Share

I'm still pretty new when it comes to Apex, so I apologize in advance if this is an easy thing to fix.

I'm trying to create a trigger that auto populates a picklist field in the Lead object, based on a value of a picklist field on the User object. So if the field on the User has a value of 'a', I want a corresponding value in a different field to be populated for any leads that this user creates.

trigger DefaultBusinessDivision on Lead (before insert) 
{     
    Map<String, String> myPickListMap = new Map<String, String> {'a'=>'a', 'b'=>'b',
        'c'=>'c', 'd'=>'d', 'e'=>'e','f'=>'f', 'g'=>'g', 'h'=>'h'};

    for (Lead a : Trigger.new)
    {        
        a.Business_Division__c = myPickListMap.get(User.Default_Business_Division__c);                  
    }      
}

Attempting to save this throws the error "Incompatible key type Schema.SObjectField for MAP", should I use a different type instead of (String, String)? Business_Division__c and Default_Business_Division__c are both picklists and are the fields I need to use to update the field on the lead page.


Attribution to: grimsvotn

Possible Suggestion/Solution #1

There isn't a global User object, you have to query the information like this:

User u = [select Default_Business_Division__c from User where Id = :UserInfo.getUserId()];
for (Lead a : Trigger.new)
{        
    a.Business_Division__c = myPickListMap.get(u.Default_Business_Division__c);                  
}

The reference User.Default_Business_Division__c is an SObjectField token used in map-like APIs.


Attribution to: Keith C

Possible Suggestion/Solution #2

The problem with the assignment is that 'User' is not a reference to the current user, instead it is a reference to the User SObject, making User.Default_Business_Division__c a field reference to the SObject field. Field references are used with dynamic SOQL.

What you are going to need to do is make a query into the User table:

User currentUser = [Select Id,Default_Business_Division__c From User Where Id = :UserInfo.getUserId()];

From there you can modify the assignment to:

a.Business_Division__c = myPickListMap.get(currentUser.Default_Business_Division__c);

Attribution to: Mike Ginou

Possible Suggestion/Solution #3

This can be solved pretty easily with either a workflow field update, or a simple formula on the lead instead of writing any apex. If it's based off the Owner of the Lead for instance, you could write a case statement based on Owner.Default_Business_Division__c.


Attribution to: James Loghry
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/31914

My Block Status

My Block Content