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
Abhishek chauhan 20Abhishek chauhan 20 

their is a field in Account Obj number of location if user enter value in that filed like 2 or 3 etc the i want to create that number of contacts ...?

Sai PraveenSai Praveen (Salesforce Developers) 
Hi Abhishek,

Does it need to delete if the number is decreased? Can you try the below code.
 
trigger CreateOrUpdateContactsOnAccount on Account (after insert, after update) {
    Set<Id> accountIds = new Set<Id>();
    Map<Id, Integer> numContactsMap = new Map<Id, Integer>();
    
    for (Account acc : Trigger.new) {
        if (Trigger.oldMap.get(acc.Id).Location__c != acc.Location__c && acc.Location__c != null) {
            Integer numContacts = Integer.valueOf(acc.Location__c);
            accountIds.add(acc.Id);
            numContactsMap.put(acc.Id, numContacts);
        }
    }
    
    if (!accountIds.isEmpty()) {
        List<Contact> existingContacts = [SELECT Id, AccountId FROM Contact WHERE AccountId IN :accountIds];
        Map<Id, List<Contact>> contactsByAccountMap = new Map<Id, List<Contact>>();
        
        for (Contact con : existingContacts) {
            if (!contactsByAccountMap.containsKey(con.AccountId)) {
                contactsByAccountMap.put(con.AccountId, new List<Contact>());
            }
            contactsByAccountMap.get(con.AccountId).add(con);
        }
        
        List<Contact> contactsToInsert = new List<Contact>();
        List<Contact> contactsToDelete = new List<Contact>();
        
        for (Id accId : accountIds) {
            Integer numContacts = numContactsMap.get(accId);
            List<Contact> existingContactsForAccount = contactsByAccountMap.containsKey(accId) ? contactsByAccountMap.get(accId) : new List<Contact>();
            
            // Create new contacts if the number has increased
            for (Integer i = existingContactsForAccount.size() + 1; i <= numContacts; i++) {
                contactsToInsert.add(new Contact(
                    FirstName = 'New Contact',
                    LastName = 'Number ' + i,
                    AccountId = accId
                ));
            }
            
            // Delete existing contacts if the number has decreased
            for (Integer i = existingContactsForAccount.size() - 1; i >= numContacts; i--) {
                contactsToDelete.add(existingContactsForAccount.get(i));
            }
        }
        
        if (!contactsToInsert.isEmpty()) {
            insert contactsToInsert;
        }
        
        if (!contactsToDelete.isEmpty()) {
            delete contactsToDelete;
        }
    }
}


 

Let me know if you face any issues.

 

If this solution helps, Please mark it as best answer.

 

Thanks,