Thursday, November 8, 2018

Trigger to count total number of contacts of account in Salesforce.com

Rollup Summary Trigger on Account in Salesforce.com

trigger numberContactsEachAccount on Contact (after insert,after delete,after undelete,after update) {

Set<Id> accountIds = new Set<Id>();
 
//for insert and undelete operation
if(Trigger.isAfter && (Trigger.isInsert || Trigger.isUndelete)){
        for(Contact con : Trigger.New){
        accountIds.add(con.AccountId);
        }
List<Account> accList = [Select Id, Number_of_Contacts__c, (Select Id from Contacts) From Account Where Id In :accountIds];

for(Account acc : accList){
        acc.Number_of_Contacts__c = acc.contacts.size();
        }
update accList;
}

//for delete operation
if(Trigger.isAfter && Trigger.isDelete){
        for(Contact con : Trigger.old){
            accountIds.add(con.AccountId);
            }
     
List<Account> accList = [Select Id, Number_of_Contacts__c, (Select Id From Contacts) From Account where Id In :accountIds];

for(Account acc : accList){
acc.Number_of_Contacts__c = acc.contacts.size();
}
update accList;
}

//for update trigger
if(Trigger.isAfter && Trigger.isUpdate){
for(Contact con : Trigger.newMap.values()){
            //comparing accountId of both new and old contacts
            if(con.AccountId != Trigger.oldMap.get(con.id).AccountId ) {
                accountIds.add(con.AccountId);
                accountIds.add(Trigger.oldMap.get(con.id).AccountId);
            }
}
List<Account> accList = [Select Id, Number_of_Contacts__c, (Select Id From Contacts) From Account Where Id In :accountIds];

for(Account acc : accList){
acc.Number_of_Contacts__c = acc.contacts.size();
}
update accList;
    }
}






Click on image to view...






No comments:

Post a Comment

Validation in flow input text field in sfdc: Maximum 255 characters limit

The input text field validate in sfdc flow behaves opposite of the generic sfdc validation rule.  Here the validation formula is evaluating ...