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.

  • Just a thought, when doing a auto population trigger you may want to add Trigger.isUpdate, and before update because edits won't be represented. This is what I did, but there may be a better way of catching Edits. – EricSSH Apr 4 '14 at 17:44

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.


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);

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.

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.