0

I am creating a trigger in which if a contact isn't associated with any account I need to create an account and associate that contact with it. I am trying this way..

trigger null_Accountid on Contact (before insert,before update)   
{  
    List<Account> accountList = new List<Account>();  
    List<Contact> contactList = new List<Contact>();  
    for(Contact cont : [SELECT id, name FROM Contact WHERE accountid='' OR accountid=null])  
    {  
            Account acc = new Account();  
            cont.accountid = acc.id;  
            acc.name = cont.lastname;  
            accountList.add(acc);            
        }  

}
2

Try this code :

trigger null_Accountid on Contact (before insert,before update)   
{   
    map<String,Account> contactAccountMap = new map<String,Account>();
    for(Contact con : trigger.new){
        if(con.AccountId == null){
            Account acc = new Account();
            acc.name = cont.lastname;  
            contactAccountMap.put(con.lastName,acc);
        }
    }
    insert  contactAccountMap.values();

    for(Contact cont : trigger.new)  
    {  
         if(cont.accountId == null){
            cont.accountid = contactAccountMap.get(cont.lastName).Id; 
        }      
    }  
}
2
  • Nice and elegant...
    – mkorman
    Feb 1 '16 at 9:29
  • always happy to help :)
    – Nitin
    Feb 1 '16 at 9:30

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.