• GregDev
  • NEWBIE
  • 0 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 2
    Replies

Hi,

 

I want to create a rollup field in Account Object with Opportunity Amount. Can any one help me on this, Actually i'm new in  trigger.

I need a Roll-up summary field on Accounts showing the number of related contacts.  Unfortunately, this is a lookup relationship so roll-up summaries are not available. 

 

I found a trigger that was written as a work around to this problem, but since I have no experience with triggers I need help revising the code.

 

I only want the contact counted if a field on the contact (Billing Contact) = True.  The trigger I found will count all contacts.  There may be 20 contacts on the account, but only 5 of them are marked billing contacts.  I only want this trigger to count the 5 contacts marked Billing.

 

How can I modify this code to accomplish this or is there a better way?

 

Thanks so much!!!

 

/* Provide summary of Number of Contacts on Account record */

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

    Contact[] cons;
    if (Trigger.isDelete)
        cons = Trigger.old;
    else
        cons = Trigger.new;

    // get list of accounts
    Set<ID> acctIds = new Set<ID>();
    for (Contact con : cons) {
            acctIds.add(con.AccountId);
    }
   
    Map<ID, Contact> contactsForAccounts = new Map<ID, Contact>([select Id
                                                            ,AccountId
                                                            from Contact
                                                            where AccountId in :acctIds]);

    Map<ID, Account> acctsToUpdate = new Map<ID, Account>([select Id
                                                                 ,Number_of_Contacts__c
                                                                  from Account
                                                                  where Id in :acctIds]);
                                                                
    for (Account acct : acctsToUpdate.values()) {
        Set<ID> conIds = new Set<ID>();
        for (Contact con : contactsForAccounts.values()) {
            if (con.AccountId == acct.Id)
                conIds.add(con.Id);
        }
        if (acct.Number_of_Contacts__c != conIds.size())
            acct.Number_of_Contacts__c = conIds.size();
    }

    update acctsToUpdate.values();

}