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
Ian Lin 585Ian Lin 585 

Need help on trigger on contact to create Account object with the contact name and associate it with contact


Ian Lin 585
Can anyone answer to the following scenario?. I need to create a account after a contact is created with the contact name as account name. If the account name with the same contact name exists assign the accountId to Id of existing account otherwise create a account with the name of the contact name and assign the new account id to contact.
My code is :
trigger CreateDefaultContact on Contact (after insert) {
       ContactDefault.createContact(trigger.new);
}

public class ContactDefault {
    
    public static void createContact(List<Contact> contactList)
    {
            List<Contact> needAcctsLst = new List<Contact>();
        for(Contact c : contactList){
            needAcctsLst.add(c);
        }
            List<Account> accountList = new List<Account>();
            List<Contact> conLst = new List<Contact>();
            for(Contact conObj : needAcctsLst)
            {
                String cname=conObj.FirstName+' '+conObj.LastName;
                Account acc = [select Id,name from Account where name=:cname LIMIT 1];
                if (acc!=null && acc.Id!=null){
                    System.debug( 'inside if ');
                    conObj.AccountId = acc.Id;
            }else{
                Account accObj = new Account();
                accObj.Name = cname;
                conObj.AccountId = accObj.Id;
                accountList.add(accObj);
                System.debug( 'inside else ');
            }
                
                conLst.add(conObj);
            }
            
            if(accountList.size() > 0)
            {
                insert accountList;
                
            }
           if(conLst.size() > 0)
            {
                System.debug( 'updating contact ');
                update conLst;
            }
    }
 }

@isTest
public class ContactDefaultTest {
    @testSetup
    static void testSetUpData() 
    {
        Account testAccount = new Account();
        testAccount.Name='aaa ttt' ;
        insert testAccount;
    }
    @istest
    public static void testMethod1(){
        Contact cont = new Contact();
        cont.FirstName='aaa';
        cont.LastName='ttt';
        insert cont;
        String cname=cont.FirstName+' '+cont.LastName;
        Account acc = [select Id,name from Account where name=:cname LIMIT 1];
        System.assertEquals(acc.Id,cont.AccountId,'Equals .. passed');
    }
}



It throws the below error. Can anyone help to fix this issue.?
Thanks.
14:59:37:160 EXCEPTION_THROWN [15]|System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CreateDefaultContact: execution of AfterInsert
14:49:50:170 FATAL_ERROR System.FinalException: Record is read-only   
Best Answer chosen by Ian Lin 585
Vijay NagellaVijay Nagella
Hi  Ian Lin 585,

Please find the Working Code.
 
trigger CreateDefaultContact on Contact (before insert) {
    
    ContactHandler.createContact(Trigger.new);
    
}
 
public class ContactHandler {
    
    public static void createContact(List<Contact> Contacts){
        
        Map<string,contact> conAccMap = new Map<string,contact>();
        
        Map<string,Account> accMap = new Map<string,Account>();
        
        List<Account> accList = new List<Account>();
        
        List<Contact> conList = new List<Contact>();
        
        string ContactName;
        
        for(Contact c : Contacts){
            ContactName = c.firstName + ' ' + c.LastName;
            conAccMap.put(ContactName,c); 
        }
        
        List<Account> accounts = [SELECT Id,Name FROM Account WHERE Name IN :conAccMap.keySet()];
        
        system.debug('=====================' + accounts);
        
        for(Account a : accounts){
            accMap.put(a.name,a);
        }
        
        
        for(Contact con : Contacts){
            
            ContactName = con.firstName + ' ' + con.LastName;
            
            if (accMap.containsKey(ContactName)){
                
                con.AccountId = accMap.get(ContactName).id;
                
            }else{
                Account acc = new Account();
                acc.Name = ContactName;
                accList.add(acc);
                accMap.put(acc.name,acc);
            }
            
            conList.add(con);
            
        }
        
        if(accList.Size() > 0){
            insert accList;
        }
        
        for(Contact con : Contacts){
            
            ContactName = con.firstName + ' ' + con.LastName;
            
            if(con.AccountId == Null){
                con.AccountId = accMap.get(ContactName).id;
            }
            
        }
        
        
    }
    
}
 
@isTest
public class ContactDefaultTest {
    
    @testSetup
    static void testSetUpData() {
        Account testAccount = new Account();
        testAccount.Name='Donald Trump' ;
        insert testAccount;
    }
    
    @istest
    public static void testMethod1(){
        
        Contact con = new Contact();
        con.FirstName='Donald';
        con.LastName='Trump';
        con.Email = 'DonaldTrump@gmail.com';
        insert con;
        
        String cname = con.FirstName + ' ' + con.LastName;
        Contact ucon  = [select Id,Name,AccountId from Contact where name = :cname LIMIT 1];
        Account acc = [select Id,name from Account where name=:cname LIMIT 1];
        System.assertEquals(acc.Id,ucon.AccountId,'Equals .. passed');
        
        Contact con1 = new Contact();
        con1.FirstName = 'Jeff';
        con1.LastName = 'Bezos';
        con1.Email = 'jeffbezos@gmail.com';
        insert con1;
        
        String cname1 = con1.FirstName + ' ' + con1.LastName;
        Contact ucon1  = [select Id,Name,AccountId from Contact where name = :cname1 LIMIT 1];
        Account acc1 = [select Id,name from Account where name=:cname1 LIMIT 1];
        System.assertEquals(acc1.Id,ucon1.AccountId,'Equals .. passed');
        
        
    }
    
}

Please Mark it as Best Answer if the Solution helps you.

Thanks,
Vijay Nagella,
Solution Architect,
Steadfast Consultancy Services

All Answers

Vijay NagellaVijay Nagella
Hi  Ian Lin 585,

Please find the Working Code.
 
trigger CreateDefaultContact on Contact (before insert) {
    
    ContactHandler.createContact(Trigger.new);
    
}
 
public class ContactHandler {
    
    public static void createContact(List<Contact> Contacts){
        
        Map<string,contact> conAccMap = new Map<string,contact>();
        
        Map<string,Account> accMap = new Map<string,Account>();
        
        List<Account> accList = new List<Account>();
        
        List<Contact> conList = new List<Contact>();
        
        string ContactName;
        
        for(Contact c : Contacts){
            ContactName = c.firstName + ' ' + c.LastName;
            conAccMap.put(ContactName,c); 
        }
        
        List<Account> accounts = [SELECT Id,Name FROM Account WHERE Name IN :conAccMap.keySet()];
        
        system.debug('=====================' + accounts);
        
        for(Account a : accounts){
            accMap.put(a.name,a);
        }
        
        
        for(Contact con : Contacts){
            
            ContactName = con.firstName + ' ' + con.LastName;
            
            if (accMap.containsKey(ContactName)){
                
                con.AccountId = accMap.get(ContactName).id;
                
            }else{
                Account acc = new Account();
                acc.Name = ContactName;
                accList.add(acc);
                accMap.put(acc.name,acc);
            }
            
            conList.add(con);
            
        }
        
        if(accList.Size() > 0){
            insert accList;
        }
        
        for(Contact con : Contacts){
            
            ContactName = con.firstName + ' ' + con.LastName;
            
            if(con.AccountId == Null){
                con.AccountId = accMap.get(ContactName).id;
            }
            
        }
        
        
    }
    
}
 
@isTest
public class ContactDefaultTest {
    
    @testSetup
    static void testSetUpData() {
        Account testAccount = new Account();
        testAccount.Name='Donald Trump' ;
        insert testAccount;
    }
    
    @istest
    public static void testMethod1(){
        
        Contact con = new Contact();
        con.FirstName='Donald';
        con.LastName='Trump';
        con.Email = 'DonaldTrump@gmail.com';
        insert con;
        
        String cname = con.FirstName + ' ' + con.LastName;
        Contact ucon  = [select Id,Name,AccountId from Contact where name = :cname LIMIT 1];
        Account acc = [select Id,name from Account where name=:cname LIMIT 1];
        System.assertEquals(acc.Id,ucon.AccountId,'Equals .. passed');
        
        Contact con1 = new Contact();
        con1.FirstName = 'Jeff';
        con1.LastName = 'Bezos';
        con1.Email = 'jeffbezos@gmail.com';
        insert con1;
        
        String cname1 = con1.FirstName + ' ' + con1.LastName;
        Contact ucon1  = [select Id,Name,AccountId from Contact where name = :cname1 LIMIT 1];
        Account acc1 = [select Id,name from Account where name=:cname1 LIMIT 1];
        System.assertEquals(acc1.Id,ucon1.AccountId,'Equals .. passed');
        
        
    }
    
}

Please Mark it as Best Answer if the Solution helps you.

Thanks,
Vijay Nagella,
Solution Architect,
Steadfast Consultancy Services
This was selected as the best answer
Ian Lin 585Ian Lin 585
Hi Vijay,
Thanks for the answer.  Best answer.