Activity Forums Salesforce® Discussions Salesforce Lookup Trigger similar to Roll Up Summary in Master-Detail

  • Shaik

    Member
    June 10, 2017 at 7:46 pm

    Taken example of account and contact.

    On Account object create a field to Count the number of child contacts and add it to your layout(in this example the field is Count_of_Contacts__c).Next create a Trigger on contact and simply copy and paste the below code.This will work in all DML operations such as Create ,Edit and Delete of a contact from an account and it is bulkified also 🙂

    trigger UpdateCountonAccount on Contact (after insert,after update,after delete) {
    set<Id> accIds = new Set<Id>();
    if(trigger.isInsert || trigger.isUpdate){
    for(contact con :trigger.new){
    accIds.add(con.accountId);
    }
    }
    if(trigger.isdelete){
    for(contact con :trigger.old){
    accIds.add(con.accountId);
    }
    }
    Map<Id, Integer> ConCountMap = new Map<Id, Integer>();
    for (AggregateResult aggRes : [
    SELECT COUNT(ID) numofCons, accountId accId
    FROM contact where accountId IN: accIds
    GROUP BY accountId
    ]) {
    Id accId = (Id) aggRes.get('accId');
    Integer numofcons = (Integer) aggRes.get('numofCons');
    ConCountMap.put(accId, numofcons);
    }
    if(!ConCountMap.isEmpty()){
    List<account> lstAcconts = new List<account>();
    List<account> lstResultAcconts = new List<account>();
    lstAcconts =[select id,name from account where id IN:ConCountMap.keySet()] ;
    for(account acc :lstAcconts){
    if(ConCountMap.containsKey(acc.id)){
    acc.Count_of_Contacts__c = ConCountMap.get(acc.id);
    lstResultAcconts.add(acc);
    }
    }
    if(!lstResultAcconts.isEmpty()){
    update lstResultAcconts;
    }
    }

    }

    Let me know if you face any issues.

    • This reply was modified 6 years, 10 months ago by  Shaik.
  • Shaik

    Member
    June 11, 2017 at 9:11 pm

    Awaiting for your comments harsitha..
    Don't forget to like or comment if the solution works.so that other people can directly jump on to the solution if they face the same issue..
    or let me know the challenges you're facing to implement the above logic..
    we are here to help..
    we really appreciate your valuable comments or likes..

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos