Saturday, December 1, 2018

Trigger On Contact Object - Auto Create Account When New Contact is Created

Trigger : Use Case - Auto Create Account When New Contact is Created

Description : This Trigger is to Create an Account When ever New Contact is Created.
Acceptance Criteria : Create New Account With Contact First Name + Contact Last Name = Account Name.

Append Both First Name & Last Name of an Contact to create new Account automatically.
Create New Contact
Account Created with Contact : First Name + Last Name

Source code

 /*   
  * Developer : Dev Pro  
  * Use Case : Trigger To Create Account When ever New Contact is Created.   
         Account Name Must Be Append with Contact First Name + Last Name   
  */  
 trigger AutoCreateAccountFromContact on Contact (before insert)   
 {  
   //Collect List Of Contacts Being Inserted without an Account  
   List createAccounts = new List();  
   for (Contact con : trigger.new)   
   {  
     if (String.isBlank(con.accountid))   
     {  
       createAccounts.add(con);  
     }  
   }  
   if (createAccounts.size() > 0)   
   {  
    List newAccounts = new List();  
    Map contactsByNameKeys = new Map();  
     //Create Account For Each Contact  
     for (Contact con : createAccounts)   
     {  
       String accountName = con.firstname + ' ' + con.lastname;  
       contactsByNameKeys.put(accountName,con);  
       Account acc = new Account(Name = accountName);  
       newAccounts.add(acc);  
     }  
     Insert newAccounts;  
     for (Account acc : newAccounts)   
     {  
       //Put Account Id's on Contacts  
       if (contactsByNameKeys.containsKey(acc.Name))   
       {  
         contactsByNameKeys.get(acc.Name).accountId = acc.Id;  
       }  
     }  
   }   
 }  


EmoticonEmoticon