Apex trigger for update Term of Monthly Amount
trigger updateTermOfMonthlyAmount on Opportunity (after insert, after update) {
for (Opportunity opp : Trigger.new) {
//delete old record first
List<Term_of_Monthly_Amount__c> terms = [SELECT Id FROM Term_of_Monthly_Amount__c WHERE Opportunity__c = :opp.Id];
if (terms.size() > 0) {
delete terms;
}
//get month difference
List<Term_of_Monthly_Amount__c> termToInsert = new List<Term_of_Monthly_Amount__c>();
Decimal amountPerMonth = opp.Amount;
Integer monthDiff = (Integer) opp.Implementation_Duration__c;
Integer seq = 1;
//loop the term of monthly amount based on frequency each product
for (Integer i=1; i<=monthDiff; i++) {
Term_of_Monthly_Amount__c tma = new Term_of_Monthly_Amount__c();
tma.Sequence__c = seq;
tma.Opportunity__c = opp.Id;
tma.Date__c = opp.Implementation_Start_Date__c.addMonths(seq-1);
DateTime dateDT = DateTime.newInstance(tma.Date__c.year(), tma.Date__c.month(), tma.Date__c.day(), 0,0,0);
String monthStr = dateDT.format('MMMMM');
tma.Period__c = monthStr;
tma.Amount__c = amountPerMonth;
termToInsert.add(tma);
seq++;
}
insert termToInsert;
}
}