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
VisithraVisithra 

Help me with the below trigger scenario

Get help with this trigger, when an no.contacts in account is entered same contacts should be created with its related account, and it should update as well.for eg when created with 3 no of contacts and while updating as 5, total 5 contacts should be created.,
i have trigger for inserted, got stuck in updation,
rigger AccountContactCaaseStudy3 on Account (after insert) {
    
   Switch On Trigger.OperationType
   {
       When AFTER_INSERT
       {
           List<Contact> conList=new List<Contact>();
           for(Account accRecord:trigger.new)
           {
               for(integer i=1;i<=accRecord.NumberofLocations__c; i++)
               {
                   Contact ConRecord=new Contact();
                   ConRecord.AccountID=accRecord.Id;
                   ConRecord.LastName= accRecord.Name +'Contact' +i;
                   conList.add(ConRecord);
                   
               }
               
           }
           if(conList.size()>0)
               insert conList;
       }
       
       
   }

}

Thanks.
SwethaSwetha (Salesforce Developers) 
HI Visithra  ,

To handle the update scenario and ensure that the correct number of contacts is created or updated based on the "NumberofLocations__c" field in the Account, you can use a combination of "after insert" and "after update" triggers.

Try this code wherein I have added logic to handle both insert and update scenarios.
trigger AccountContactCaseStudy3 on Account (after insert, after update) {
    if (Trigger.isAfter) {
        if (Trigger.isInsert) {
            createContacts(Trigger.new);
        } else if (Trigger.isUpdate) {
            Set<Id> accountIds = new Set<Id>();
            for (Account accRecord : Trigger.new) {
                // Check if the NumberofLocations__c field has changed
                if (Trigger.oldMap.get(accRecord.Id).NumberofLocations__c != accRecord.NumberofLocations__c) {
                    accountIds.add(accRecord.Id);
                }
            }
            if (!accountIds.isEmpty()) {
                List<Account> accountsToUpdate = [SELECT Id, NumberofLocations__c FROM Account WHERE Id IN :accountIds];
                createOrUpdateContacts(accountsToUpdate);
            }
        }
    }
}

// Method to create contacts on insert
private static void createContacts(List<Account> accounts) {
    List<Contact> conList = new List<Contact>();
    for (Account accRecord : accounts) {
        for (Integer i = 1; i <= accRecord.NumberofLocations__c; i++) {
            Contact conRecord = new Contact();
            conRecord.AccountId = accRecord.Id;
            conRecord.LastName = accRecord.Name + 'Contact' + i;
            conList.add(conRecord);
        }
    }
    if (!conList.isEmpty()) {
        insert conList;
    }
}

// Method to create or update contacts on update
private static void createOrUpdateContacts(List<Account> accounts) {
    List<Contact> conList = new List<Contact>();
    for (Account accRecord : accounts) {
        Integer numOfContacts = accRecord.NumberofLocations__c;
        List<Contact> existingContacts = [SELECT Id, LastName FROM Contact WHERE AccountId = :accRecord.Id ORDER BY CreatedDate ASC];

        // Delete extra contacts if any
        if (existingContacts.size() > numOfContacts) {
            delete existingContacts.subList(numOfContacts, existingContacts.size());
            existingContacts = existingContacts.subList(0, numOfContacts);
        }

        // Update existing contacts if the NumberofLocations__c is reduced
        for (Integer i = 0; i < numOfContacts; i++) {
            if (existingContacts.size() > i) {
                existingContacts[i].LastName = accRecord.Name + 'Contact' + (i + 1);
            } else {
                Contact conRecord = new Contact();
                conRecord.AccountId = accRecord.Id;
                conRecord.LastName = accRecord.Name + 'Contact' + (i + 1);
                conList.add(conRecord);
            }
        }
    }

    // Perform DML operations
    if (!conList.isEmpty()) {
        insert conList;
    }
    if (!accounts.isEmpty()) {
        update accounts;
    }
}

If this information helps, please mark the answer as best. Thank you