+ Start a Discussion

Copy Lead Owner Name to Another Field Based on Owner Profile

I'm pretty new to APEX, and am hoping someone might have some direction for me on this...


I'm trying to figure out how to copy the Lead Owner name to another user lookup field on the same Lead (fieldname=Sales_Developer__c) - when the lead owner changes, but only if the owner profile equals “Sales Developer”.


From what I understand of the Lead Owner field, you can’t extract the profile attribute directly from the Lead Owner field – so I’ve created a separate field called “Owner_Copy__c” (shout out to michaelforce and others for this code) – and then would like to reference the profile attribute from that new lookup field.


Anyway – I hope this makes sense. Here is the code I have so far to copy the user name to the Owner_Copy__c field:



trigger ownerCopy on Lead (before Insert, before Update) {

    // handle arbitrary number of opps
    for(Lead x : Trigger.New){

        // Has Owner changed?
        if (x.OwnerID != x.Owner_Copy__c) {

            // check that owner is a user (not a queue)
            if( ((String)x.OwnerId).substring(0,3) == '005' ){
                x.Owner_Copy__c = x.OwnerId;

            // in case of Queue we clear out our copy field
                x.Owner_Copy__c = null;



I’m stuck on figuring out how to restrict the process to only update the Sales_Developer__c field when the profile criteria is met.


Am I headed in the right direction – or how would you approach this?


I know the following isn’t valid code, but I’m wondering if I can do something like this also?:



if (x.Owner_Copy__c.Profile.Name == 'Sales Development') {
            x.Sales_Developer__c = x.OwnerId;

            x.Sales_Developer__c = null;


Thank you




if (x.Owner_Copy__c.Profile.Name == 'Sales Development')

 This code will return null for Profile Name, because related fields are not loaded in a trigger.

You need to explicitly query the Profile Name.

something like

Set<Id> setOwnerID = new Set<ID>();
for(Lead x : Trigger.New){
  //Copy ownerID in a set

//Keep this outside of loop.
Map<Id,User> mpUserProfile = [Select Profile.Name from User
where Id IN :setOwnerID];

for(Lead x:Trigger.New) {
  User user = mpUserProfile.get(x.Owner_Copy__c);
  if(user.Profile.Name == 'Sales Developer') {
    //Logic here.


Hope that helps.