I have 2 custom object(Master Contract and Contact Person), i have lookup relationship between them. I have related list Contact Person in Master Contract Object with button named Recalculation. In Contact Person i have Amount field and in Master contract i have Total Amount field. If i create new contact person(with new amount) and then i click Recalculation button, it will sum the new amount and the old one. The total amount will be shown at Total Amount field in Master Contract. I already have trigger which is executed without using button. But i want this trigger to execute when i click the button. Can anyone help me to solve this problem? Here i type the trigger and image. Thanks.
trigger AddContractMasterTotalAmount on Contact_Person__c (after insert, after delete, after update) {
if(Trigger.isInsert){
try {
for (Contact_Person__c cp : Trigger.new){
Contract_Master__c cm = [SELECT Id, Total_Amount__c FROM Contract_Master__c WHERE Id = :cp.Contact_ID__c];
Decimal amount = 0.0;
List<Contact_Person__c> l_cp = [SELECT Id, Amount__c FROM Contact_Person__c WHERE Contact_Id__c = :cm.Id];
for(Contact_Person__c am_cp : l_cp) {
amount += am_cp.Amount__c;
}
cm.Total_Amount__c = amount;
update cm;
}
} catch (Exception e) {
System.debug(e);
}
}
if(Trigger.isAfter) {
if(Trigger.isUpdate){
try {
for (Contact_Person__c cp : Trigger.old){
Contract_Master__c cm = [SELECT Id, Total_Amount__c FROM Contract_Master__c WHERE Id = :cp.Contact_ID__c];
Decimal amount = 0.0;
List<Contact_Person__c> l_cp = [SELECT Id, Amount__c FROM Contact_Person__c WHERE Contact_Id__c = :cm.Id];
for(Contact_Person__c am_cp : l_cp) {
amount += am_cp.Amount__c;
}
cm.Total_Amount__c = amount;
update cm;
}
} catch (Exception e) {
System.debug(e);
}
}
if(Trigger.isDelete){
try {
for (Contact_Person__c cp : Trigger.old){
Contract_Master__c cm = [SELECT Id, Total_Amount__c FROM Contract_Master__c WHERE Id = :cp.Contact_ID__c];
Decimal amount = 0.0;
List<Contact_Person__c> l_cp = [SELECT Id, Amount__c FROM Contact_Person__c WHERE Contact_Id__c = :cm.Id];
for(Contact_Person__c am_cp : l_cp) {
amount += am_cp.Amount__c;
}
cm.Total_Amount__c = amount;
update cm;
}
} catch (Exception e) {
System.debug(e);
}
}
}
}