Very Imp Programs

1. Trigger to update count, sum, min, max, avg of child records on Parent object:


Trigger ContactAggregateResult on Contact(after insert, after update, after delete, 

                                          after undelete)

{

    

    Set<Id> accountIdSet = new Set<Id>();

    Map<Id, Account> accountMap = new Map<Id, Account>();

    

    if (Trigger.isInsert || Trigger.IsUpdate|| Trigger.isUndelete) {

        for(Contact con: Trigger.new){

            if(con.AccountId != null){

                accountIdSet.add(con.AccountId);

            }

        }

    }

    

    if (Trigger.isDelete) {

        for(Contact con: Trigger.old){

            if(con.AccountId != null){

                accountIdSet.add(con.AccountId);

            }

        }

    }

    

    if(accountIdSet != null){

        for(AggregateResult ar: [SELECT count(Id) contactCount, sum(Amount__c) sumAmount, 

                                 avg(Amount__c) avgAmount, Max(Amount__c) maxAmount,

                                 min(Amount__c) minAmount, AccountId FROM Contact 

                                 WHERE AccountId in: accountIdSet GROUP BY AccountId ])

        {

            Account acc = new Account();

            acc.Id = (Id)ar.get('AccountId');

            acc.Count_of_Contacts__c = (Integer)ar.get('contactCount');

            acc.Sum_of_Contacts_Amount__c = (Decimal)ar.get('sumAmount');

            acc.Max_of_Contacts_Amount__c = (Decimal)ar.get('maxAmount');

            acc.Min_of_Contacts_Amount__c = (Decimal)ar.get('minAmount');

            acc.Average_Of_Contacts_Amount__c = (Decimal)ar.get('avgAmount');

            accountMap.put(acc.Id, acc);

        }

    }

    if(accountMap != null){

        update accountMap.values();

    }

}


=========================================================================


2. Trigger to count child records and display in parent record in case of lookup relationship. 


Trigger ContactCountTrigger on Contact(After insert, After Delete,  After Undelete, After Update) {

    

    Set < Id > setAccountIds = new Set < Id > ();

    if (Trigger.isInsert || Trigger.isUndelete || Trigger.IsUpdate) {

        for (Contact con: Trigger.new) {

            setAccountIds.add(con.AccountId);

        }

    }

    if (Trigger.isDelete) {

        for (Contact con: Trigger.old) {

            setAccountIds.add(con.AccountId);

        }

    }

    List < Account > listAccs = [Select id, name, number_of_contacts__c,

                                 (Select id from contacts) from Account

                                 where Id in: setAccountIds];

    for (Account acc: listAccs) {

        acc.number_of_contacts__c = acc.contacts.size();

    }

    update listAccs;

}


=========================================================================


3. Trigger to restrict the creation of duplicate Primary Contact for the same Account:


Trigger PrimaryContactChecking on Contact(before insert, before update) {


    Set < Id > accountIdSet = new Set < id > ();

    Map < Id, List < Contact >> accountIdContactMap = new Map < Id, List < Contact >> ();

    Account acc = new Account();

    for (Contact con: Trigger.New) {

        accountIdSet.add(con.AccountId);

    }

    for (Contact con: [SELECT Id, IsPrimaryContact__c, AccountId FROM Contact

                       WHERE AccountId =: accountIdSet AND IsPrimaryContact__c = TRUE

                      ]) 

    {

        if (accountIdContactMap.containsKey(con.AccountId)) {

            accountIdContactMap.get(con.AccountId).add(con);

        } else {

            accountIdContactMap.put(con.AccountId, new List < Contact > ());

            accountIdContactMap.get(con.AccountId).add(con);

        }

    }

    for (Contact con: Trigger.New) {

        if ((accountIdContactMap.containsKey(con.AccountId)) &&

            (con.AccountId != NULL) && (con.IsPrimaryContact__c == TRUE)) {

                {

                    con.IsPrimaryContact__c.addError('Primary Contact already exists');

                    con.addError('Primary Contact already exists');

                }

            }

    }

}


=========================================================================


4. Apex trigger to update child record when parent record is updated. 


trigger ContactUpdate on Account(after update) {


    Map < Id, Account > mapAccount = new Map < Id, Account > ();

    List < Contact > listContact = new List < Contact > ();

    

    for (Account acct: trigger.new)

        mapAccount.put(acct.Id, acct);

    

    listContact = [SELECT MailingStreet, MailingCity, AccountId FROM Contact

                   WHERE AccountId IN: mapAccount.keySet()

                  ];

    

    if (listContact.size() > 0) {

        for (Contact con: listContact) {

            con.MailingStreet = mapAccount.get(con.AccountId).BillingStreet;

            con.MailingCity = mapAccount.get(con.AccountId).BillingCity;

        }

        update listContact;

    }

}


=========================================================================


5. Apex trigger to update parent record when child record is updated. 


Trigger UpdateDescription on Contact(after insert, after update) { 


    Map < ID, Account > accIdMap = new Map < ID, Account > (); 

    //Making it a map instead of list for easier lookup

    

    List < Id > accIdSet = new List < Id > ();

    for (Contact childObj: Trigger.new {

        accIdSet.add(childObj.AccountId);

    }

         

         accIdMap = new Map < Id, Account > ([SELECT id, Description,

                                              (SELECT ID, Description FROM Contacts) FROM Account 

                                              WHERE ID IN: accIdSet]);

         

         for (Contact con: Trigger: new) {

             Account myParentOpp = accIdMap.get(con.AccountId);

             myParentOpp.Description = con.Description;

         }

         update accIdMap.values();

}

         

=========================================================================








No comments:

Post a Comment