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
mng0827mng0827 

Roll-up Summary Trigger

Hi,

I'm trying to create a roll-up summary trigger for contacts to account. However, I get the following error:

Incompatible key type Schema.SObjectField for MAP<Id,Account>

Can someone help me with this? Here's my code:

trigger UpdateAccountAfterContactInsert on Contact (after insert, after update, after delete) {

    //unique Account object Ids
    private Set<Id> accountIdSet = new Set <Id>();
   
    //hold list of Account Record to be updated
    private List<Account> accountListUpdatable = new List<Account>();
   
    //when insert & update the Contact
    if(trigger.isInsert || trigger.isUpdate){
       
        for(Contact c: Trigger.new){
            accountIdSet.add(c.AccountId);
        }
    }
    //when update & delete the Contact
    if (Trigger.isUpdate || Trigger.isDelete){
        for(Contact c: Trigger.old){
            AccountIdSet.add(c.AccountId);
        }
    }
    //select the Account list
    Map<Id, Account> accountMap = new Map<ID, Account> ([Select Id from Account WHERE ID IN: accountIds]);
   
    for(Account a: [Select ID,(Select ID FROM Contacts)from Account WHERE ID IN:accountIds]){
       
        accountMap.get(account.ID) = a.Contacts.size();//assigning Size
        accountListUpdatable.add(accountMap.get(account.ID));
    }
    if(accountListUpdatable != NULL && accountListUpdatable.size()>0)
        UPDATE accountListUpdatable;
}

Saurabh DhobleSaurabh Dhoble
First up, replace this block - 
for(Account a: [Select ID,(Select ID FROM Contacts)from Account WHERE ID IN:accountIds]){
       
        accountMap.get(account.ID) = a.Contacts.size();//assigning Size
        accountListUpdatable.add(accountMap.get(account.ID));
    }
with this -
for(Account a: [Select ID,(Select ID FROM Contacts)from Account WHERE ID IN:accountIdSet]){
       Account acc = accountMap.get(a.ID);
       acc = a.Contacts.size();//assigning Size
       accountListUpdatable.add(accountMap.get(a.ID));
    }
You were using "account" in place of "a"
The above is still going to error -
why are you trying to assign a.Contacts.size() to a variable - let me know.

Saurabh DhobleSaurabh Dhoble
Did this work ?