Trigger to Sum values (like Lookup relationship)
trigger NewLucy on Contact (after insert, after delete, after update) {
if(Trigger.isInsert){
try {
for (Contact co : Trigger.new) {
Account po = [SELECT Id,SumAllContactCurrency__c FROM Account WHERE Id = :co.AccountId];
List<Contact> l_co = [SELECT Id,amount__c FROM Contact WHERE AccountId = :po.Id];
for(Contact am_co : l_co) {
amount += am_co.Amount__c;
}
po.SumAllContactCurrency__c = amount;
update po;
}
} catch (Exception e) {
System.debug(e);
}
}
if(Trigger.isAfter) {
if(Trigger.isUpdate) {
try {
for (Contact co : Trigger.old) {
Account po = [SELECT Id,SumAllContactCurrency__c FROM Account WHERE Id = :co.AccountId];
List<Contact> l_co = [SELECT Id,amount__c FROM Contact WHERE AccountId = :po.Id];
for(Contact am_co : l_co) {
amount += am_co.Amount__c;
}
po.SumAllContactCurrency__c = amount;
update po;
}
} catch (Exception e) {
System.debug(e);
}
}
if(Trigger.isDelete){
try {
for (Contact co : Trigger.old){
Account po = [SELECT Id,SumAllContactCurrency__c FROM Account WHERE Id = :co.AccountId];
List<Contact> l_co = [SELECT Id,amount__c FROM Contact WHERE AccountId = :po.Id];
for(Contact am_co : l_co) {
amount += am_co.Amount__c;
}
po.SumAllContactCurrency__c = amount;
update po;
}
} catch (Exception e) {
System.debug(e);
}
}
}
}