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
Tushar Tyagi 4Tushar Tyagi 4 

auto-create Contact record

Hey, team, 
I m Facing issue with the below mentioned Bold point.
Please help.


• Create a custom checkbox field on Account and name it ‘Create Contact?’
• Create a number field on Account and name it as ‘No. Of Contacts to create’.
• Create an autonumber field on Account name it as “Account Number”.
• Create a custom number field on Contact and name it as “Contact Count”.
• Each time an account record is saved with checkbox marked as true; with a given number value, that many contact records should be created with following actions
o LastName = Account Number - Contact Count
o FirstName = Account Name
o Phone = Phone
o Billing Address = Billing Address
o Shipping Address = Shipping Address
o Contact Count = which number of contact this is with respect to Account. So for example Account ‘Acme’ already had 5 Contacts and you are creating 6th Contact it should say Contact Count as 6th, 7th etc.
public class AccountAutomation 
{

    public void contactHandler(List<Account> AccList)
    {
    try{
    List<Contact> ConList = new List<Contact>();
    map<id,decimal> AccMap=new map<id,decimal>(); 
       
        for(Account Acc : AccList)
        {
            if(Acc.Create_Contact__c == true)
            {
                
            	AccMAp.put(Acc.id, Acc.No_Of_Contacts_to_create__c);
             	if(Accmap.size()>0 && Accmap!=Null)
                {
                    for(ID AccID : AccMap.keySet())
                    {
                       for(integer i = 0;i<AccMap.get(Accid);i++) 
                       {
                           Contact Con = new Contact();
                           Con.accountId         = Accid;
                           Con.LastName          = Acc.Account_Number__c + '-' + con.Contact_Count__c;
                           Con.FirstName                     = Acc.Name;
                           Con.Phone	                        = Acc.Phone;
                           con.MailingStreet                 =acc.BillingStreet;
               			   con.MailingCity             =acc.BillingCity;
                		   con.MailingState           =acc.BillingState;
                		   con.MailingPostalCode =acc.BillingPostalCode;
                		   con.MailingCountry       =acc.BillingCountry;
                          
                           ConList.add(Con);
                       }
              
                    }
                }
                if(ConList.Size()>0 && ConList!=Null)
                insert ConList;
                
                
            }
        }
        
    }
         catch (Exception e)
        {
            system.debug('An Exception has occured = '+e);
        }

}
}

 
Best Answer chosen by Tushar Tyagi 4
Amit Chaudhary 8Amit Chaudhary 8
Try to update contact Last Name like below

Con.LastName = acc.Account_Number__c + '-' + sizeCont + numberSuffix;

try to update your code like below
public class AccountAutomation {

    public void contactHandler(List<Account> AccList) {
        try 
        {

            List<Contact> ConList = new List<Contact>();
            map<id, decimal> AccMap = new map<id, decimal>();
            Set<ID> setAccId = new Set<ID>();
            for (Account Acc : AccList) 
            {
                if (Acc.Create_Contact__c == true) 
                {
                    setAccId.add(Acc.id);
                }
            }

            List<Account> lstAccount = [SELECT id,Create_Contact__c,Account_Number__c,No_Of_Contacts_to_create__c,Name,Phone,
                                                BillingStreet,BillingCity,BillingState,BillingPostalCode,BillingCountry,
                                        (Select id from Contacts)
                                        FROM Account
                                        WHERE id in :setAccId
                                        ];
            
            For(Account acc: lstAccount)
            {
                if(acc.Create_Contact__c == true)
                {
                    List<Contact> lstCont = acc.Contacts;
                    
                    integer sizeCont =0;
                    if(lstCont != null && lstCont.size() > 0 )
                    {
                        // Check Existing Contact Size
                        sizeCont = lstCont.size();
                    }

                    for (integer i = 0; i < acc.No_Of_Contacts_to_create__c ; i++) 
                    {
                        sizeCont++;
                        
                        String numberSuffix = getNumberSuffix( sizeCont );

                        Contact Con = new Contact();
                        Con.accountId = acc.id;
                        Con.LastName = acc.Account_Number__c + '-' + sizeCont + numberSuffix;
                        Con.FirstName = acc.Name;
                        Con.Phone = acc.Phone;
                        con.MailingStreet = acc.BillingStreet;
                        con.MailingCity = acc.BillingCity;
                        con.MailingState = acc.BillingState;
                        con.MailingPostalCode = acc.BillingPostalCode;
                        con.MailingCountry = acc.BillingCountry;
                        //con.Contact_Count__c = numberSuffix;
                        ConList.add(Con);
                    }   
                }
            }   
            if (ConList.Size() > 0 && ConList != Null)
                insert ConList;
        }
        catch (Exception e) 
        {
            system.debug('An Exception has occured = ' + e);
        }

    }
    
    public String getNumberSuffix(Integer n) 
    {
        if (n == null) {
            return '';
        }

        if (n >= 11 && n <= 13) {
            return 'th';
        }

        Integer modResult = Math.mod(n, 10);        
        if (modResult == 1) { 
            return 'st'; 
        } else if (modResult == 2) { 
            return 'nd'; 
        } else if (modResult == 3) { 
            return 'rd'; 
        } else { 
            return 'th';
        }
    }   
    
}

Let us know if this will help you

All Answers

om gupta(sfdc)om gupta(sfdc)
so suppose there are 1account  and 2  contacts are there is  No_Of_Contacts_to_create__c field value will be 2 here or we have to update that also ?
Asif Ali MAsif Ali M
Hi Tushar

Your code needs to be refactored first and then implement the logic to calculate the St, Nd, Th suffix based on the number. 
Find the refactored code below. You just need to add a method (getNumberSuffix(Integer n) ) to calculate the suffix as mentione here (https://salesforce.stackexchange.com/questions/41787/how-can-i-format-a-day-from-a-date-as-2nd-intead-of-2-or-3rd-instead-of-3?answertab=active#tab-top

I have not tested this code so you may get syntax error. 
 
public class AccountAutomation {

    public void contactHandler(List<Account> AccList) {
        try {
            List<Contact> ConList = new List<Contact>();
            map<id, decimal> AccMap = new map<id, decimal>();

            // Prepare the map with # contacts to be created
            for (Account Acc : AccList) {
                if (Acc.Create_Contact__c == true) {
                    AccMAp.put(Acc.id, Acc.No_Of_Contacts_to_create__c);
                }
            }

            // Create contacts for each account
            if (Accmap.size() > 0 && Accmap != Null) {
                for (ID AccID : AccMap.keySet()) {
                    for (integer i = 0; i < AccMap.get(Accid); i++) {
                        
                        // implement a method getNumberSuffix as mentioned here https://salesforce.stackexchange.com/questions/41787/how-can-i-format-a-day-from-a-date-as-2nd-intead-of-2-or-3rd-instead-of-3?answertab=active#tab-top 
                        String numberSuffix = i+1 + getNumberSuffix(i+1);
                        
                        Contact Con = new Contact();
                        Con.accountId = Accid;

                        // NOT SURE IF YOU WANT TO HAVE SUFFIX HERE ON LAST NAME
                        Con.LastName = Acc.Account_Number__c + '-' + numberSuffix;
                        Con.FirstName = Acc.Name;
                        Con.Phone = Acc.Phone;
                        con.MailingStreet = acc.BillingStreet;
                        con.MailingCity = acc.BillingCity;
                        con.MailingState = acc.BillingState;
                        con.MailingPostalCode = acc.BillingPostalCode;
                        con.MailingCountry = acc.BillingCountry;

                        // ASSUMING THIS FIELD IS STRING TYPE
                        con.Contact_Count__c = numberSuffix;
                        ConList.add(Con);
                    }
                }
            }
            

            if (ConList.Size() > 0 && ConList != Null)
                insert ConList;

        } catch (Exception e) {
            system.debug('An Exception has occured = ' + e);
        }

    }
}

 
Amit Chaudhary 8Amit Chaudhary 8
Try to update your code like below
public class AccountAutomation {

    public void contactHandler(List<Account> AccList) {
        try 
		{

			List<Contact> ConList = new List<Contact>();
            map<id, decimal> AccMap = new map<id, decimal>();
			Set<ID> setAccId = new Set<ID>();
            for (Account Acc : AccList) 
			{
                if (Acc.Create_Contact__c == true) 
				{
					setAccId.add(Acc.id);
                }
            }

			List<Account> lstAccount = [SELECT id,Create_Contact__c,Account_Number__c,No_Of_Contacts_to_create__c,Name,Phone,
												BillingStreet,BillingCity,BillingState,BillingPostalCode,BillingCountry,
										(Select id from Contacts)
										FROM Account
										WHERE in in :setAccId
										];
			
			For(Account acc: lstAccount)
			{
				if(acc.Create_Contact__c == true)
				{
					List<Contact> lstCont = acc.Contacts;
					
					integer sizeCont =0;
					if(lstCont != null && lstCont.size() > 0 )
					{
						// Check Existing Contact Size
						sizeCont = lstCont.size();
					}

                    for (integer i = 0; i < acc.No_Of_Contacts_to_create__c ; i++) 
					{
						sizeCont++;
						
						String numberSuffix = getNumberSuffix( sizeCont );

						Contact Con = new Contact();
						Con.accountId = acc.id;
						Con.LastName = acc.Account_Number__c + '-' + numberSuffix;
						Con.FirstName = acc.Name;
						Con.Phone = acc.Phone;
						con.MailingStreet = acc.BillingStreet;
						con.MailingCity = acc.BillingCity;
						con.MailingState = acc.BillingState;
						con.MailingPostalCode = acc.BillingPostalCode;
						con.MailingCountry = acc.BillingCountry;
						con.Contact_Count__c = numberSuffix;
						ConList.add(Con);
					}	
				}
			}	
            if (ConList.Size() > 0 && ConList != Null)
                insert ConList;
        }
		catch (Exception e) 
		{
            system.debug('An Exception has occured = ' + e);
        }

    }
	
    public String getNumberSuffix(Integer n) 
	{
        if (n == null) {
            return '';
        }

        if (n >= 11 && n <= 13) {
            return 'th';
        }

        Integer modResult = Math.mod(n, 10);        
        if (modResult == 1) { 
            return 'st'; 
        } else if (modResult == 2) { 
            return 'nd'; 
        } else if (modResult == 3) { 
            return 'rd'; 
        } else { 
            return 'th';
        }
    }	
	
}

Let us know if this will help you
 
Asif Ali MAsif Ali M
Great catch Amit. Thanks for adding existing lengh logic and implementing the getNumberSuffix.
Tushar Tyagi 4Tushar Tyagi 4
Hey Amit,
Thanks for the solution, But when I am updating the Account with increased value in  "No. Of Contacts to create", the count starts again from 0, which makes duplicate contacts.
Like If 4 contacts are there and I update the Account with "No. Of Contacts to create"=2 the, Please Look for duplicate values in ContactIt should make it as 5 and 6 but it is naming them again from 1.
Please check the screen shot
Amit Chaudhary 8Amit Chaudhary 8
Try to update contact Last Name like below

Con.LastName = acc.Account_Number__c + '-' + sizeCont + numberSuffix;

try to update your code like below
public class AccountAutomation {

    public void contactHandler(List<Account> AccList) {
        try 
        {

            List<Contact> ConList = new List<Contact>();
            map<id, decimal> AccMap = new map<id, decimal>();
            Set<ID> setAccId = new Set<ID>();
            for (Account Acc : AccList) 
            {
                if (Acc.Create_Contact__c == true) 
                {
                    setAccId.add(Acc.id);
                }
            }

            List<Account> lstAccount = [SELECT id,Create_Contact__c,Account_Number__c,No_Of_Contacts_to_create__c,Name,Phone,
                                                BillingStreet,BillingCity,BillingState,BillingPostalCode,BillingCountry,
                                        (Select id from Contacts)
                                        FROM Account
                                        WHERE id in :setAccId
                                        ];
            
            For(Account acc: lstAccount)
            {
                if(acc.Create_Contact__c == true)
                {
                    List<Contact> lstCont = acc.Contacts;
                    
                    integer sizeCont =0;
                    if(lstCont != null && lstCont.size() > 0 )
                    {
                        // Check Existing Contact Size
                        sizeCont = lstCont.size();
                    }

                    for (integer i = 0; i < acc.No_Of_Contacts_to_create__c ; i++) 
                    {
                        sizeCont++;
                        
                        String numberSuffix = getNumberSuffix( sizeCont );

                        Contact Con = new Contact();
                        Con.accountId = acc.id;
                        Con.LastName = acc.Account_Number__c + '-' + sizeCont + numberSuffix;
                        Con.FirstName = acc.Name;
                        Con.Phone = acc.Phone;
                        con.MailingStreet = acc.BillingStreet;
                        con.MailingCity = acc.BillingCity;
                        con.MailingState = acc.BillingState;
                        con.MailingPostalCode = acc.BillingPostalCode;
                        con.MailingCountry = acc.BillingCountry;
                        //con.Contact_Count__c = numberSuffix;
                        ConList.add(Con);
                    }   
                }
            }   
            if (ConList.Size() > 0 && ConList != Null)
                insert ConList;
        }
        catch (Exception e) 
        {
            system.debug('An Exception has occured = ' + e);
        }

    }
    
    public String getNumberSuffix(Integer n) 
    {
        if (n == null) {
            return '';
        }

        if (n >= 11 && n <= 13) {
            return 'th';
        }

        Integer modResult = Math.mod(n, 10);        
        if (modResult == 1) { 
            return 'st'; 
        } else if (modResult == 2) { 
            return 'nd'; 
        } else if (modResult == 3) { 
            return 'rd'; 
        } else { 
            return 'th';
        }
    }   
    
}

Let us know if this will help you
This was selected as the best answer
Tushar Tyagi 4Tushar Tyagi 4
Thanks, Amit, it worked and it successfully completed my requirements.
But just want to know.
What if I want to add a manual contact correspond to any account and that contact should follow the same naming convention like we are using above (LastName = Account Number - Contact Count).
so what should I need to do for that?
Do I need to write a separate trigger on account for that or I can achieve that from this trigger too?
Please advice.
Amit Chaudhary 8Amit Chaudhary 8
Yes you need to create one more Trigger for naming. I will suggest you to create new thread for new question. So that lots of other person can also help you