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
sgsssgss 

assign contact to account on basis of domain

I want to write trigger for folloeing use case
Match the contact email field of newly created contact to the website field of ACCOUNT  and assign that contact to account using trigger.
Niraj Kr SinghNiraj Kr Singh
Hi Supriya,

try this and let me know if it works for you.
trigger ContactTrigger on Contact (before Insert) {
	ContactTriggerHandler.mapContactToAcc(trigger.new);
}
public class ContactTriggerHandler {
	
	public static void mapContactToAcc(List<Contact> newContactList) {
		Map<String, List<Contact>> conEmailMap = new Map<String, List<Contact>>();
		List<Contact> tempContact;
		for(Contact objCon : newContactList) {
			if(objCon.Email != null) {
				tempContact.clear();
				if(conEmailMap.containsKey(objCon.Email)) {
					tempContact = conEmailMap.get(objCon.Email);
					tempContact.add(objCon);
					conEmailMap.put(objCon.Email, tempContact);
				}
				else {
					conEmailMap.put(objCon.Email, new List<Contact>{objCon});
				}
			}	
		}
		
		if(!conEmailMap.isEmpty()) {
			for(Account objAcc : [SELECT Id, Website FROM Account WHERE Website In:conEmailMap.keySet()]) {
				for(Contact objCon : conEmailMap.get(objAcc.Website)) {
					objCon.AccountId = objAcc.Id;
				}
			}
		}
	}
}
Works for your mark ur answer.

Thanks
Niraj
sgsssgss
User-added image

Its giving error on insert of contact.
Akshay_DhimanAkshay_Dhiman

Hi Supriya,

Just Try this Below Code For Requirement --
--------------------Trigger Code---------------------------
trigger AccountContactInsertion on Contact (before insert ) {
 ContactAccountInsertionBasedOnMail.ContactTriggerHandler(trigger.New);
 }
 --------------Its Related Handler -------------------
 public class ContactAccountInsertionBasedOnMail {
    public static void ContactTriggerHandler(List<Contact> conList)
    {
        Map<String,List<Contact>> ContactVsAccountMap = new Map<String,List<Contact>>();
        for(Contact conLoop : conList)
        {
            if(conLoop.Email!=null)
            {
                if(!ContactVsAccountMap.containsKey(conLoop.Email))
                {
                    ContactVsAccountMap.put(conLoop.Email, new List<Contact>());
                }
                ContactVsAccountMap.get(conLoop.Email).add(conLoop);
            }
        }
        
        for(Account accLoop : [Select Id, Website from Account Where Website IN:ContactVsAccountMap.keySet()])
        {
            for(Contact con : conList)
            {
                if(con.Email!=null && accLoop.Website!=null)
                {
                    if(con.Email == accLoop.Website)
                    {
                        con.AccountId = accLoop.Id;
                    }  
                }
                
            }
        }
    }
}



Thanks 
Akshay
sgsssgss
Hey akshay,
This one is inserting only the contact record. and Related account is not getting assosciated.
Akshay_DhimanAkshay_Dhiman
Hi Supriya,

Just Re-Check It Once In my Org Its working Completely Fine The Contact gets associated with its Matching Website Account. 
Niraj Kr SinghNiraj Kr Singh
Hi Supriya,
It working fine in my org any how you update this line of code 
​List<Contact> tempContact; // At Line no 5.
With this code:
​List<Contact> tempContact = new List<Contact>();

iit will work now.

 if it works for you, mark your answer to help others.

Thanks
Niraj
Ajay K DubediAjay K Dubedi
Hi Supriya,
Please try the following:
-------Trigger------
trigger assign contact on Contact(before insert, before update){
  assignContact.triggerClass(Trigger.New);
}

--------related class-------------
public class assignContact {
    
    public static void triggerClass(List<Contact> ContactList) {
        Map<String, List<Contact>> domainVsContactMap = new Map<String, List<Contact>>();
        
        for(Contact c: ContactList) {
            if(c.Email != null) {
                List<String> domainsplit=c.email.split('@',2);
                String domain=domainsplit[1];
                                system.debug('Domain---->>>: '+domain);

                if(domainVsContactMap.containsKey(domain)) {
                    List<Contact>temp=domainVsContactMap.get(domain);
                    
                    temp.add(c);
                    domainVsContactMap.put(domain, temp);
                }
                else {
                    domainVsContactMap.put(domain, new List<Contact>{c});
                }
            }    
        }
        
        if(!domainVsContactMap.isEmpty()) {
            system.debug('Not Empty');
            List<Account> accList=new List<Account>();
            accList=[SELECT Id, Website FROM Account WHERE Website In:domainVsContactMap.keySet()];
            system.debug('accList'+accList);
            for(Account acc : accList) {
                system.debug('Account: '+acc);
                List<Contact>conList=new List<Contact>();
                conlist=domainVsContactMap.get(acc.Website);
                for(Contact c : conList) {
                                    system.debug('Contact: '+ c);

                    c.AccountId = acc.Id;
                }
            }
        }
    }
}

Please let me know if you have any query.

Thanks
Ajay Dubedi
sgsssgss
Thanks a lot Ajay 
sgsssgss
Hey Ajay can you provide test class for the code as well? considering all positive negative bulk scenario
Ajay K DubediAjay K Dubedi
Hi Supriya,

Its good to know that it works for you.
Below is the test class considering the negative and positive scenario.
 
@isTest
private class assignContact_Test {
    @isTest
      static void assignContactBasedOnAccountDomain_PositiveTest(){
          
              List<Account> accInsert=new List<Account>();
            for(integer i=0;i<2;i++){
                    Account acc=new Account();
                    acc.Name='Test Account Flipkart';
                acc.Website='flipkart.com';
                    accInsert.add(acc);
            }
          for(integer i=0;i<2;i++){
                    Account acc=new Account();
                    acc.Name='Test Account Gmail';
                acc.Website='gmail.com';
                    accInsert.add(acc);
            }
        
         Insert accInsert;
        
         List<contact> contactInsert=new List<contact>();
        
         for(integer i=0;i<50;i++){
                    contact c=new contact();
                     c.LastName='Test Contact Flipkart';
                    c.email='test@flipkart.com';
                    contactInsert.add(c);
            }
          for(integer i=0;i<50;i++){
                    contact c=new contact();
                     c.LastName='Test Contact Gmail';
                    c.email='test@gmail.com';
                    contactInsert.add(c);
            }
            
        
         Insert contactInsert;
          test.startTest();
         List<Account> acc=new List<Account>();
         acc=[select id from account];
          system.assertEquals(4, acc.size());
         List<Contact> con=new List<Contact>();
         con=[select ID, account.name from contact where account.website='flipkart.com'];
        //  system.debug('------------->>'+con);
          system.assertEquals(50, con.size());
          con.clear();
         con=[select ID from contact where account.website='gmail.com'];
          system.assertEquals(50, con.size());
           con.clear();
            con=[select accountId from contact where accountid <> null];
            system.assertEquals(100, con.size());
        test.stopTest();
    }
    
          
    @isTest
      static void assignContactBasedOnAccountDomain_NegativeTest(){
          
              List<Account> accInsert=new List<Account>();
            for(integer i=0;i<2;i++){
                    Account acc=new Account();
                    acc.Name='Test Account Flipkart';
                acc.Website='flipkart.com';
                    accInsert.add(acc);
            }
          for(integer i=0;i<2;i++){
                    Account acc=new Account();
                    acc.Name='Test Account Gmail';
                acc.Website='google.com';
                    accInsert.add(acc);
            }
        
         Insert accInsert;
        
         List<contact> contactInsert=new List<contact>();
        
         for(integer i=0;i<50;i++){
                    contact c=new contact();
                     c.LastName='Test Contact Flipkart';
                    c.email='test@flipkart.com';
                    contactInsert.add(c);
            }
          for(integer i=0;i<50;i++){
                    contact c=new contact();
                     c.LastName='Test Contact Gmail';
                    c.email='test@gmail.com';
                    contactInsert.add(c);
          }
         Insert contactInsert;
          test.startTest();
         List<Account> acc=new List<Account>();
         acc=[select id from account];
          system.assertEquals(4, acc.size());
         List<Contact> con=new List<Contact>();
         con=[select ID, account.name from contact where account.website='flipkart.com'];
        //  system.debug('------------->>'+con);
          system.assertEquals(50, con.size());
          con.clear();
         con=[select ID from contact where account.website='gmail.com'];
          system.assertEquals(0, con.size());
           con.clear();
            con=[select accountId from contact];
            system.assertEquals(100, con.size());
        test.stopTest();
    }
     @isTest
      static void assignContactBasedOnAccountDomain_Negative2Test(){
         
         List<contact> contactInsert=new List<contact>();
        
         for(integer i=0;i<50;i++){
                    contact c=new contact();
                     c.LastName='Test Contact Flipkart';
                    c.email='test@flipkart.com';
                    contactInsert.add(c);
            }
          for(integer i=0;i<50;i++){
                    contact c=new contact();
                     c.LastName='Test Contact Gmail';
                    c.email='test@gmail.com';
                    contactInsert.add(c);
            }
            
        
         Insert contactInsert;
          test.startTest();
        
       
         List<Contact> con=new List<Contact>();
         con=[select ID, account.name from contact where account.website='flipkart.com'];
        //  system.debug('------------->>'+con);
          system.assertEquals(0, con.size());
          con.clear();
         con=[select ID from contact where account.website='gmail.com'];
          system.assertEquals(0, con.size());
           con.clear();
            con=[select accountId from contact where accountid=null];
            system.assertEquals(100, con.size());
        test.stopTest();
    }
}

If it completes your requirement then please mark this as Best Answer to help others.
Please let me know if you have any query.

Thanks!
Ajay Dubedi
 
sgsssgss
Hey Ajay Thanks,
But assignContactBasedOnAccountDomain_PositiveTest 
assignContactBasedOnAccountDomain_NegativeTest these two test methods are failing.
Can you suggest some solution?
Ajay K DubediAjay K Dubedi
Hi Supriya,

The possible cause of this is due to some other trigger running in your org. Because in my org it's working totally fine, if you really want to check it then you can try to deactivate all the trigger on account and contact object.
Please respond with the error message or status message, so that I can figure this out.

Thanks!
Ajay Dubedi