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
Naofumi KunNaofumi Kun 

Trigger to update the Contact Owner depending on Email field value

I'm new to coding and I'm practicing by creating a trigger that will update the Contact Owner depending on the Email field value.
For example, I have the Email field value is test@gmail.com then it will try to look for User that has test@gmail.com email then it will update the Contact Owner.

This is what I've done so far:
 
Set<String> conEmail = new set<String>();
    List<String> UsrId = new List<String>();
    Map<String, Id> UsrMap = new map<String, Id>();
    
    for(Contact con : trigger.new ){
        if(con.Email != null){
            conEmail.add(con.Email);
        }
    }
    
    List<User> userEmail = [SELECT Id, Name, Email FROM User WHERE Email In: conEmail];
    for(User u : userEmail){
        UsrMap.put(u.Email, u.Id);     
    }
    
    for(Contact c : trigger.new){
        if(UsrMap.containsKey(c.Email)){
            c.OwnerId = UsrMap.get(c.Email);
        }
    }
Any ideas on why Owner is not being updated when I edit any contact record.

Thank you!
RKSalesforceRKSalesforce
Hello,

If you have not created trigger then please create trigger on Contact Object.

Use below code. This code will work in case of insert and update:
trigger updateAssignContactOwner on Contact(before insert, before update){
	Set<String> conEmail = new set<String>();
    List<String> UsrId = new List<String>();
    Map<String, Id> UsrMap = new map<String, Id>();
    
    for(Contact con : trigger.new ){
        if(con.Email != null){
            conEmail.add(con.Email);
        }
    }
    
    List<User> userEmail = [SELECT Id, Name, Email FROM User WHERE Email In: conEmail];
    for(User u : userEmail){
        UsrMap.put(u.Email, u.Id);     
    }
    
    for(Contact c : trigger.new){
        if(UsrMap.containsKey(c.Email)){
            c.OwnerId = UsrMap.get(c.Email);
        }
    }
}

Please mark as best answer if helped.

Regards,
Ramakant
Naofumi KunNaofumi Kun
Hi Ramakant,

I've already created a contact trigger and used before insert and before update.

I tried updating the any fields from contact but the Owner field is not being updated.

I also tried to remove 
if(UsrMap.containsKey(c.Email))
still it does not work.