RollUp Summary for lookUp

If we have two objects may be custom or standard linked with lookup relationship and we want to create rollup summary field for parents then, I am discussing a senario

I want to count the number of records of child object in parent when they are linked with look up relationship so I have Account, Contact and Opportunity . I want to count the no of contacts and no of opportunities on account object then then we have to write a trigger on child mean one trigger on contact and one for opportunity before that I have to create 2 custom Fields of number data type on account
  1. Field Name : No Of Contact(s), API Name: No_of_Contact_s__c Digit(4,0)
  2. Field Name: No Of Opportunity, API Name :No_of_Opportunity_s__c(4,0)
Trigger on contact
trigger ContactCount on Contact (after insert, after delete,after undelete,after update) {
Set<ID> aId = new Set<ID>();
if(Trigger.isInsert || Trigger.isUndelete || Trigger.isUpdate){
for(Contact con : Trigger.New){
aId.add(con.AccountId);
}
List<account> acc = [select id,No_of_Contact_s__c from Account where Id in:aId];
List<contact> con = [select id from contact where AccountId in :aId];
for(Account a : acc){
a.No_of_Contact_s__c = con.size();
}
update acc;
}
if(Trigger.isDelete){
for(Contact con : Trigger.old){
aId.add(con.AccountId);
}
List<account> acc = [select id,No_of_Contact_s__c from Account where Id in:aId];
List<contact> con = [select id from contact where AccountId in :aId];
for(Account a : acc){
a.No_of_Contact_s__c=con.size();
}
update acc;
}
}
Trigger on Opportunity

trigger Opportunityopp on Opportunity (after insert, after delete,after undelete,after update) {
Set<ID> aId = new Set<ID>();
Double i=0;
if(Trigger.isInsert || Trigger.isUndelete){
for(Opportunity opp : Trigger.New){
if(opp.accountId!=null)
aId.add(opp.AccountId);
}
List<account> acc = [select id,No_of_Opportunity_s__c from Account where Id in:aId];
List<Opportunity> oppl = [select id from Opportunity where AccountId in :aId];
for(Account a : acc){
a.No_of_Opportunity_s__c=oppl.size();
}
update acc;
}
if(Trigger.isDelete){
for(Opportunity opp : Trigger.old){
if(opp.AccountId!=null)
aId.add(opp.AccountId);
}
List<account> acc = [select id,No_of_Opportunity_s__c from Account where Id in:aId];
List<Opportunity> oppl = [select id,Amount from Opportunity where AccountId in :aId];
for(Account a : acc){
a.No_of_Opportunity_s__c=oppl.size();
}
update acc;
}
}

Comments