How to write a rollup summary trigger for a lookup relationship

https://github.com/abhinavguptas/Salesforce-Lookup-Rollup-Summaries

The above link from Abhinav solves your problem

If you need for more than one object would recommend to try the excellent tool from Andrew

http://andyinthecloud.com/2013/07/07/new-tool-declarative-rollups-for-lookups/

And if you have requirement for only one object ,you can prefer jeff solution as well

http://blog.jeffdouglas.com/2009/07/30/roll-up-summary-fields-with-lookup-relationships-part-1/


Here is an example :

  1. Account (Parent Object)
  2. Contact (Child Object).
  3. Contact_Recs__c (Roll up summary field/Custom Field).
  4. accountid (Lookup field).

Code sample:

trigger CountContactsnew on Contact (after insert, after delete, after undelete) {

    List<id> accIdList = new List<id>();
    if(Trigger.isInsert || Trigger.isUndelete){
        For(Contact con1 : Trigger.new){
            accIdList.add(con1.accountid);
        }
    }
    if(Trigger.isDelete){
        For(Contact con1 : Trigger.old){
            accIdList.add(con1.accountid);
        }
    }
    List<Account> accUpdateList = new List<Account>();
    For(Account acc : [SELECT Contact_Recs__c,(SELECT id FROM Contacts) FROM Account WHERE id =: accIdList]){
        acc.Contact_Recs__c = acc.Contacts.size();
        accUpdateList.add(acc);
    }
    try{
        update accUpdateList;
    }Catch(Exception e){
        System.debug('Exception :'+e.getMessage());
    }
}