I have a search vfp which is integrated with SAP. I use it for on demand upserting records from SAP into SF Account. Whenever I upsert records in SF, I need a trigger to count the related records from another custom object. Note: I cannot use master detail relationship because records from custom object may not always have related records.
The trigger only fires when the upserted record is updated. How can I make it to fire also upon insert. I tried using after insert but the record is read only.
Triggger Class
Public void triggerAccount(list<account> accountList){
List<Id> accountId = new List<Id>();
List<Account> accT = new List<Account>();
List<Contract__c> A1_contracts= new List<Contract__c>();
List<Contract__c> A2_contracts= new List<Contract__c>();
List<Contract__c> A3_contracts= new List<Contract__c>();
List<Contract__c> A4_contracts= new List<Contract__c>();
List<Contract__c> A5_contracts= new List<Contract__c>();
List<Contract__c>Cont_A1_qry = new List<Contract__c>();
List<Contract__c>Cont_A2_qry = new List<Contract__c>();
List<Contract__c>Cont_A3_qry = new List<Contract__c>();
List<Contract__c>Cont_A4_qry = new List<Contract__c>();
List<Contract__c>Cont_A5_qry = new List<Contract__c>();
for(Account a: accountList){
accT.add(a);
accountId.add(a.Id);
}
Cont_A1_qry = [Select Id FROM Contract__c WHERE Account__c = : accountId AND Brand__c = 'a1'];
Cont_A2_qry = [Select Id FROM Contract__c WHERE Account__c = : accountId AND Brand__c = 'a2'];
Cont_A3_qry = [Select Id FROM Contract__c WHERE Account__c = : accountId AND Brand__c = 'a3'];
Cont_A4_qry = [Select Id FROM Contract__c WHERE Account__c = : accountId AND Brand__c = 'a4'];
Cont_A5_qry = [Select Id FROM Contract__c WHERE Account__c = : accountId AND Brand__c = 'a5'];
for(Account updateAcc : accountList){
integer iA1 = Cont_A1_qry.size();
integer iA2 = Cont_A2_qry.size();
integer iA3 = Cont_A3_qry.size();
integer iA4 = Cont_A4_qry.size();
integer iA5 = Cont_A5_qry.size();
updateAcc.No_of_A1_Contracts__c = iA1 ;
updateAcc.No_of_A2_Contracts__c = iA2;
updateAcc.No_of_A3_Contracts__c = iA3;
updateAcc.No_of_A4_Contracts__c = iA4;
updateAcc.No_of_A5_Contracts__c = iA5;
}
}
Trigger
trigger AccountTrigger on Account (before update) {
If(Trigger.IsUpdate){
AccountClass acc = new AccountClass();
acc.triggerAccount(Trigger.new);
}
}