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
kpriya Aggarwalkpriya Aggarwal 

Please help on this Apex Trigger.

I want to show the no of  contacts in Account ilike this:
If I have 5 contacts under an Account then these contacts should be shown in account as 1,2,3,4,5 (This sequence must be show in Text field (Show_Contacts__c) )
 
Best Answer chosen by kpriya Aggarwal
Abdul KhatriAbdul Khatri
Here is the code with less code and the Test Class for all the operations Insert, Update and Delete with 100% coverage

Trigger
trigger ShowContactNumberSequenceOnAccount on Contact (after insert, after update, after delete) {
    
    List<Contact> contactNewList = (trigger.isDelete ? trigger.old : trigger.new);
    Set<Id> idAccountSet = new Set<Id>();
    
    for(Contact contact : contactNewList) {        
        if (contact.AccountId != null) {
            idAccountSet.add(contact.AccountId);
        }
    }
    
    if(idAccountSet.isEmpty()) return;
    
    List<Account> accountList = [SELECT Id, (SELECT Id FROM Contacts) FROM Account Where Id IN :idAccountSet];
    String strSequence;
    for(Account account : accountList) {
        strSequence = '';
        if(account.Contacts == null) continue;
        
        for(Integer i = 1 ; i <= account.Contacts.size() ; i++) {
            strSequence = strSequence == '' ? String.ValueOf(i) : strSequence + ',' + String.ValueOf(i);
        }
        account.Show_Contacts__c = strSequence;
    }
	update accountList;
}

Test Class
@isTest
public class ShowContactNumberSequenceOnAccountTest {
	
    static testmethod void test_ShowContactNumberSequenceOnAccount_onInsert() {
        
        Account account = new Account (Name = 'Test');
        insert account;
        
        Contact contact1 = new Contact (LastName = 'Test1', AccountId = account.Id);
        insert contact1;
        
        Contact contact2 = new Contact (LastName = 'Test2', AccountId = account.Id);
        insert contact2;    
        
        Account accountTest = [Select Id, Show_Contacts__c From Account Where Name = 'Test'];
        System.assert(accountTest.Show_Contacts__c == '1,2');
    }
    
    static testmethod void test_ShowContactNumberSequenceOnAccount_onUpdate() {
        
        Account account = new Account (Name = 'Test');
        insert account;
        
        Contact contact1 = new Contact (LastName = 'Test1', AccountId = account.Id);
        insert contact1;
        
        Contact contact2 = new Contact (LastName = 'Test2', AccountId = account.Id);
        insert contact2;  
        
        contact2.LastName = 'Test2Update';
        update Contact2;
        
        Account accountTest = [Select Id, Show_Contacts__c From Account Where Name = 'Test'];
        System.assert(accountTest.Show_Contacts__c == '1,2');
    } 
    
    static testmethod void test_ShowContactNumberSequenceOnAccount_onDelete() {
        
        Account account = new Account (Name = 'Test');
        insert account;
        
        Contact contact1 = new Contact (LastName = 'Test1', AccountId = account.Id);
        insert contact1;
        
        Contact contact2 = new Contact (LastName = 'Test2', AccountId = account.Id);
        insert contact2;  
        
        delete Contact2;
        
        Account accountTest = [Select Id, Show_Contacts__c From Account Where Name = 'Test'];
        System.assert(accountTest.Show_Contacts__c == '1');
    }     
}

 

All Answers

Rahul.MishraRahul.Mishra
Hi kpriya,

Please find the trigger code which populates the required seqence on account after insert of contact record:
trigger showSequence on Contact (After insert) {
    
    Set<Id> setParentAccountId = new Set<Id>();
    List<Account> lstAccountToUpdate = new List<Account>();
    
    for(Contact con : trigger.new) {
        if(con.AccountId != null)
         setParentAccountId.add(con.AccountId);
    }
   
   for(Account acc : [Select Id, Show_Contacts_c, (Select Id From Contacts)From Account Where Id =:setParentAccountId]) {
       Integer lstSize = acc.Contacts.size();
       system.debug('lst size is'+lstSize);
       
       if(lstSize > 0) {
           String strAppend = acc.Show_Contacts_c;
           if(strAppend == null) {
               strAppend = ''+lstSize;
           }else {
           strAppend = strAppend+','+lstSize;
           }
           lstAccountToUpdate.add(new Account(Id = acc.Id, Show_Contacts_c = strAppend));
       } 
   }
   
   if(!lstAccountToUpdate.isEmpty())
    update lstAccountToUpdate;
}

Please mark my answer as a best if you have got your answer.

Thanks,
Rahul 
Steven NsubugaSteven Nsubuga
Trigger ShowContacts on Contact (after insert, after update, after delete) {
    
    Set<Id> accountIds = new Set<Id>();
    List<Account> accountsToUpdate = new List<Account>();

    for (Contact c : Trigger.new) {
        accountIds.add(c.accountId);
    }

    if (Trigger.isUpdate || Trigger.isDelete) {
        for (Contact ac : Trigger.old) {
            accountIds.add(ac.accountId);
        }
    }

    // get a map of the accounts with the number of items
    Map<id,Account> popMap = new Map<id,Account>([select id, Show_Contacts__c from Account where id IN :accountIds]);

    List<AggregateResult> ars = [SELECT accountId, count(Id) FROM Contact WHERE accountId IN :accountIds group by accountId];
    
    for (AggregateResult ar : ars) {
        
        String accountId = String.valueOf(ar.get('accountId'));
        Integer ctCount = Integer.valueOf(ar.get('expr0'));
        String cts = '';
        
         for (Integer s = 1; s < ctCount + 1; s++) {
            cts = cts + ',' + s;
        }
        popMap.get(String.valueOf(ar.get('accountId'))).Show_Contacts__c = cts.substring(1);
    }
    update popMap.values();
}

test class
@isTest
private class ShowContactsTest {

    @isTest static void testTrigger(){
    
        // Create Account records
        List<Account> accounts = new List<Account>();
        for (Integer s = 1; s < 3; s++) {
            Account acct = new Account(Name = 'TestAccount' + s);
            accounts.add(acct);
        }
        insert accounts;
        
        // Create Contact records
        List<Contact> contacts = new List<Contact>();
        for (Integer s = 0; s < 2; s++) {
            Contact ct = new Contact(AccountId = accounts[s].Id, LastName = 'TestContact' + s);
            contacts.add(ct);
        }
        insert contacts;
        
        List<Account> accounts2 = [SELECT Name, Show_Contacts__c FROM Account];
        for (Account acct : accounts2) {
            System.assertEquals('1', acct.Show_Contacts__c);
        }
        
        // Create additional Contact records for 1 of the Accounts
        List<Contact> contacts3 = new List<Contact>();
        for (Integer s = 0; s < 2; s++) {
            Contact ct = new Contact(AccountId = accounts[0].Id, LastName = 'TestContact-' + s);
            contacts3.add(ct);
        }
        insert contacts3;
        Account account1 = [SELECT Show_Contacts__c FROM Account WHERE Id =:accounts[0].Id LIMIT 1];
        
        System.assertEquals('1,2,3', account1.Show_Contacts__c);
    }
}


Abdul KhatriAbdul Khatri
Here is the code with less code and the Test Class for all the operations Insert, Update and Delete with 100% coverage

Trigger
trigger ShowContactNumberSequenceOnAccount on Contact (after insert, after update, after delete) {
    
    List<Contact> contactNewList = (trigger.isDelete ? trigger.old : trigger.new);
    Set<Id> idAccountSet = new Set<Id>();
    
    for(Contact contact : contactNewList) {        
        if (contact.AccountId != null) {
            idAccountSet.add(contact.AccountId);
        }
    }
    
    if(idAccountSet.isEmpty()) return;
    
    List<Account> accountList = [SELECT Id, (SELECT Id FROM Contacts) FROM Account Where Id IN :idAccountSet];
    String strSequence;
    for(Account account : accountList) {
        strSequence = '';
        if(account.Contacts == null) continue;
        
        for(Integer i = 1 ; i <= account.Contacts.size() ; i++) {
            strSequence = strSequence == '' ? String.ValueOf(i) : strSequence + ',' + String.ValueOf(i);
        }
        account.Show_Contacts__c = strSequence;
    }
	update accountList;
}

Test Class
@isTest
public class ShowContactNumberSequenceOnAccountTest {
	
    static testmethod void test_ShowContactNumberSequenceOnAccount_onInsert() {
        
        Account account = new Account (Name = 'Test');
        insert account;
        
        Contact contact1 = new Contact (LastName = 'Test1', AccountId = account.Id);
        insert contact1;
        
        Contact contact2 = new Contact (LastName = 'Test2', AccountId = account.Id);
        insert contact2;    
        
        Account accountTest = [Select Id, Show_Contacts__c From Account Where Name = 'Test'];
        System.assert(accountTest.Show_Contacts__c == '1,2');
    }
    
    static testmethod void test_ShowContactNumberSequenceOnAccount_onUpdate() {
        
        Account account = new Account (Name = 'Test');
        insert account;
        
        Contact contact1 = new Contact (LastName = 'Test1', AccountId = account.Id);
        insert contact1;
        
        Contact contact2 = new Contact (LastName = 'Test2', AccountId = account.Id);
        insert contact2;  
        
        contact2.LastName = 'Test2Update';
        update Contact2;
        
        Account accountTest = [Select Id, Show_Contacts__c From Account Where Name = 'Test'];
        System.assert(accountTest.Show_Contacts__c == '1,2');
    } 
    
    static testmethod void test_ShowContactNumberSequenceOnAccount_onDelete() {
        
        Account account = new Account (Name = 'Test');
        insert account;
        
        Contact contact1 = new Contact (LastName = 'Test1', AccountId = account.Id);
        insert contact1;
        
        Contact contact2 = new Contact (LastName = 'Test2', AccountId = account.Id);
        insert contact2;  
        
        delete Contact2;
        
        Account accountTest = [Select Id, Show_Contacts__c From Account Where Name = 'Test'];
        System.assert(accountTest.Show_Contacts__c == '1');
    }     
}

 
This was selected as the best answer