I am trying to go through the following code posted by another individual:

trigger CountContactsnew on Contact (after insert, after delete, after undelete) {

    List<id> accIdList = new List<id>();
    if(Trigger.isInsert || Trigger.isUndelete){
        For(Contact con1 : Trigger.new){
        For(Contact con1 : Trigger.old){
    List<Account> accUpdateList = new List<Account>();
    For(Account acc : [SELECT Contact_Recs__c,(SELECT id FROM Contacts) FROM Account WHERE id =: accIdList]){
        acc.Contact_Recs__c = acc.Contacts.size();
        update accUpdateList;
    }Catch(Exception e){
        System.debug('Exception :'+e.getMessage());

However I am uncertain as to what the line:

acc.Contact_Recs__c = acc.Contacts.size();

accomplishes. Could someone please let me know.


acc.Contacts.size() - returns the count of Contacts of Account under iteration.

This is a part of subquery. So when you have a query with inner join, another name for it is subquery:

SELECT Contact_Recs__c, (SELECT Id FROM Contacts) FROM Account

To access the list child contacts under an account, it can be accessed by Account.Contacts

and the statement indicates the its assigned to Contact_Recs__c field on Account.

Added: As suggested by Toby, adding the purpose of trigger.

Rollup summary fields are not supported if the objects don't have a master detail relationship. Relation between Account and Contact is hybrid and doesn't support rollups.

You can also use Declarative Rollup Summary Tool, if you want to avoid writing code. Its a super awesome tool.

  • 1
    You may want to add a note about how you can't create roll-up fields on standard objects which is likely what this code is trying to replicate. – gNerb Mar 23 '17 at 15:28
  • @Toby, In question it was simply mentioned about that line. good suggestion, will add it. thank you! – Raul Mar 23 '17 at 15:45
  • 1
    Glad to see you added a recommendation to use DLRS. – Adrian Larson Mar 23 '17 at 21:50
  • @RahulSharma so out of curiosity, and since I am new, how would this differ if it were for a SUM rather than COUNT – dgelinas21 Mar 26 '17 at 22:20
  • @dgelinas21, in that case you'd need to sum up the values from appropriate field from child to parent object. – Raul Mar 26 '17 at 22:23

Well, the variable acc is an instance of an Account object.

In the query returning this account: [SELECT Contact_Recs__c,(SELECT id FROM Contacts) FROM Account WHERE id =: accIdList], there is a nested query selecting the ids of the contacts related to this account: (SELECT id FROM Contacts).

So the statement acc.Contacts.size() returns the size of the related contacts.

Note: The variable Contact_Recs__c must be of type Number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.