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
sumit dsumit d 

trigger to create contact on Account when Account is inserted

Hi All,
When a new Account is created, create a new Contact that has the following data points:
First Name = “Info”
Last Name = “Default”
Email = “info@websitedomain.tld”
Only_Default_Contact = TRUE
When the Account has more than 1 Contact, update Only_Default_Contact to FALSE.
Best Answer chosen by sumit d
KumartoonKumartoon
Hi Sumit and Mohd Nabeel
you can try the below code:

Trigger 1: on Account object(for creating the default Contact)
trigger AccountDefaultContactTrigger on Account (after insert) {

    if(Trigger.isAfter){
        if(Trigger.isInsert){
            AccountContactHandler.createDefaultContactForAccount(Trigger.newMap);
        }
    }
}

Trigger 2: on Contact object (to check the respective account, if it has more than 1 contact)
trigger CountAccountOnContactTrigger on Contact (after insert) {
	if(Trigger.isAfter){
        if(Trigger.isInsert){
            AccountContactHandler.checkContactCountOnAccount(Trigger.New);
        }
    }
}

Apex Handler class for both above Triggers
public class AccountContactHandler {

    public static void createDefaultContactForAccount(Map<Id,Account> accountNewMap){
        List<Contact> conList = new List<Contact>();
        List<Account> accList = [select Id,Name from Account where Id IN:accountNewMap.keyset()];
    
        for(Account acc:accList){
            acc.Only_Default_Contact__c=true;
            conList.add(new Contact(FirstName='Info',LastName='Default',Email='info@websitedomain.tld',AccountId=acc.Id));
        } 
        update accList;
        if(conList.size()>0){
            insert conList;
        }
       
    }
    
    public static void checkContactCountOnAccount(List<Contact> contactList){
       
        Set<Id> accIds = new Set<Id>();
        for(Contact con:contactList){
            accIds.add(con.AccountId);
        }   
  
        List<Account> accList = [select id,(select Id,Name from Contacts) from Account where Id IN:accIds];
        for(Account acc:accList){
            if(acc.Contacts.size()>1){
                acc.Only_Default_Contact__c=false;
               
            }
        }
    	update accList;   
       
    }
}

All Answers

SandhyaSandhya (Salesforce Developers) 
Hi,

Below is the sample code modify according to your needs.
 
// Trigger on Account object to handle insert and update.
trigger insertcontact on Account (before insert,after insert,after update) {
    if(trigger.isbefore && trigger.isinsert) {
		ContactNameUpdate.accountmethod(Trigger.new);
    }
    
    if(trigger.isafter && trigger.isinsert) {
		ContactNameUpdate.contactMethod(Trigger.new);
    }
}
 
public class ContactNameUpdate {
	// Method to handle the contact inserts.
	public static void contactMethod(List<Account> accList){
		List<Contact> conList = new List<Contact>();
		for(Account acc : accList) {
			  Contact con = new Contact(AccountId = acc.Id);
			  List<String> nameStr = acc.Name.split(' ');
			  if(nameStr.size()>0)
				 con.LastName = nameStr[0];
			  if(nameStr.size()>1)
				  con.FirstName = nameStr[1];
			  conList.add(con);
		}
		insert conList;		
	}
}

Please mark it as solved if my reply was helpful. It will make it available for other as the proper solution.
                                             
Best Regards
Sandhya
 
 
Jolly_BirdiJolly_Birdi
Hello Sumit,

Please try this below Code:
Add these two triggers:
trigger AccountTrigger on Account (after insert) {
    if(trigger.isafter && trigger.isinsert) {
		ContactNameUpdate.newContactCreated(Trigger.new);
    }
}
 
trigger ContactTrigger on Contact (after insert) {
    if(trigger.isafter && trigger.isinsert) {
		ContactNameUpdate.updateCheckboxOnAccount(Trigger.new);
    }
}

Add this as class file:
public class ContactNameUpdate {
	// Method to handle the contact inserts.
	public static void newContactCreated(List<Account> accList){
		List<Contact> conList = new List<Contact>();
		for(Account acc : accList) {
			  Contact con = new Contact(AccountId = acc.Id);
			  List<String> nameStr = acc.Name.split(' ');
			  if(nameStr.size()>0)
				 con.LastName = nameStr[0];
			  if(nameStr.size()>1)
				  con.FirstName = nameStr[1];
				  
			con.Email = 'info@websitedomain.tld';
			con.Only_Default_Contact__c = TRUE;
			conList.add(con);
		}
		insert conList;		
	}
	public static void updateCheckboxOnAccount(List<Contact> contactList){
		Set<Id> accountIds = new Set<Id>();
		for(Contact con : contactList) {
			 accountIds.add(con.AccountId);
		}
		
		List<Account> updatedAccounts = new List<Account>();
		for(AggregateResult ar : [select count(id) , AccountId from Contact where AccountId IN :accountIds group by AccountId having count(id)  >1 ]){
			updatedAccounts.add(new Account(Id = (Id)ar.get('AccountId'), Only_Default_Contact__c=false));    
		}
		
		if(!updatedAccounts.isEmpty())
			update updatedAccounts;
	}
}

Please like and mark this as best answer if you find it positive.

Thanks
​​​​​​​Jolly Birdi
Mohd NabeelMohd Nabeel
can you explain me this line 
con.Only_Default_Contact__c = TRUE;
how it will access it? contact is the child of Account how wil it access the Accounts field?
KumartoonKumartoon
Hi Sumit and Mohd Nabeel
you can try the below code:

Trigger 1: on Account object(for creating the default Contact)
trigger AccountDefaultContactTrigger on Account (after insert) {

    if(Trigger.isAfter){
        if(Trigger.isInsert){
            AccountContactHandler.createDefaultContactForAccount(Trigger.newMap);
        }
    }
}

Trigger 2: on Contact object (to check the respective account, if it has more than 1 contact)
trigger CountAccountOnContactTrigger on Contact (after insert) {
	if(Trigger.isAfter){
        if(Trigger.isInsert){
            AccountContactHandler.checkContactCountOnAccount(Trigger.New);
        }
    }
}

Apex Handler class for both above Triggers
public class AccountContactHandler {

    public static void createDefaultContactForAccount(Map<Id,Account> accountNewMap){
        List<Contact> conList = new List<Contact>();
        List<Account> accList = [select Id,Name from Account where Id IN:accountNewMap.keyset()];
    
        for(Account acc:accList){
            acc.Only_Default_Contact__c=true;
            conList.add(new Contact(FirstName='Info',LastName='Default',Email='info@websitedomain.tld',AccountId=acc.Id));
        } 
        update accList;
        if(conList.size()>0){
            insert conList;
        }
       
    }
    
    public static void checkContactCountOnAccount(List<Contact> contactList){
       
        Set<Id> accIds = new Set<Id>();
        for(Contact con:contactList){
            accIds.add(con.AccountId);
        }   
  
        List<Account> accList = [select id,(select Id,Name from Contacts) from Account where Id IN:accIds];
        for(Account acc:accList){
            if(acc.Contacts.size()>1){
                acc.Only_Default_Contact__c=false;
               
            }
        }
    	update accList;   
       
    }
}
This was selected as the best answer
Suraj Tripathi 47Suraj Tripathi 47
Hi Sumit,
"Try this code."
trigger ContactInsertion on Account (before insert,after insert,after update) {
    if(trigger.isbefore && trigger.isinsert) {
        ContactNameUpdate.accountmethod(Trigger.new);
    }
    
    if(trigger.isafter && trigger.isinsert) {
        ContactNameUpdate.contactMethod(Trigger.new);
    }
}


public class UpdateCon {
    public static void contactUpdate(List<Account> accList){
        List<Contact> conList = new List<Contact>();
        for(Account acc : accList) {
              Contact con = new Contact(AccountId = acc.Id);
              List<String> nameStr = acc.Name.split(' ');
              if(nameStr.size()>0)
                 con.LastName = nameStr[0];
              if(nameStr.size()>1)
                  con.FirstName = nameStr[1];
              conList.add(con);
        }
        insert conList;        
    }
}

If you find your Solution then Mark this as Best Answer

Thank you!
​​​​​​​
Regards,
Suraj Tripathi
Butesh SinglaButesh Singla

Hi,

Follow this link:

sharath k 8sharath k 8
trigger ContactsCreation on Account (after insert) 
{
 list<contact> listContact = new list<contact>();
 for(Account acc:trigger.new)
 {
  for(integer i=0;i<acc.NumberofLocations__c;i++)
  {
 contact newContact=new contact();
 newContact.accountid=acc.Id;
 newContact.lastname='contact'+i;
 listContact.add(newContact);
 }
 }
 if(listContact.size()>0 && listContact!=null)
{
 insert listContact;
 }