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
thirumaghal baskarthirumaghal baskar 

In Trigger how to update the contacts on updating the count field(custom field) in Account. for example. if i update the count as 3 three contacts should be created for the corresponding account, if i update the count to 5 , two more records be created

Best Answer chosen by thirumaghal baskar
Deepali KulshresthaDeepali Kulshrestha
Hi Thirumaghal,
I am assuming that your requirement is that when an account is updated when the number of contacts should be created based on the value of the custom field and if the value is greater than the previous value then the remaining contacts should be created.
You can achieve this by putting the conditions and comparing the values and then creating the contacts based on the result of the difference.

Here I am creating contacts as per the "Number of Employees" field in the Account.

My trigger for this is as follows:

trigger CreateContacts on Account(after insert){
if(Trigger.isAfter && Trigger.isInsert)
{
TriggerOnAccount.createEmployeeAccount(Trigger.new);    
}
    
}

And the helper class for this trigger is:
public class TriggerOnAccount {
    public static void createEmployeeAccount(List<Account>accountList)
        {
            try {
                System.debug('Starting');
                List<Contact>contactList=new List<Contact>();
                for(Account acc:accountList){
                    if(acc.NumberOfEmployees!=Null)
                    {
                        for(Integer i=0;i<acc.NumberOfEmployees;i++)
                            {


                                Contact contactObject=new Contact();
                                contactObject.AccountId=acc.Id;
                                contactObject.LastName='Employee_Account_'+i;
                                contactList.add(contactObject);


                            }

                    }

                }
                if(contactList.size()>0)
                {
                    insert contactList;

                }


            }catch (Exception e)
            {
                System.debug(e.getMessage());
            }
        }

}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks and Regards,
Deepali Kulshrestha