0

There are two object Contract and Subscription.There is Lookup relationship between both. Contract is parent and Subscription is child object.

The child-relationship name between two is: Subscriptions

I have written Trigger on Subscription object to Count number of subscriptions and display that to Contract. Below is my trigger:

trigger CountContract on SBQQ__Subscription__c (after INSERT, after UPDATE, 
after DELETE ) {
Set <Id> contractIds = new Set <Id>();
List <Contract> lstContractsToUpdate = new List <Contract>();
if(Trigger.isInsert){
for(SBQQ__Subscription__c s:trigger.new){
    contractIds.add(s.SBQQ__Contract__r.id);
}
}
if(Trigger.isUpdate|| Trigger.isDelete){
for(SBQQ__Subscription__c s:trigger.old){
    contractIds.add(s.SBQQ__Contract__r.id);
 }
}
system.debug(contractIds);
for(Contract con:[SELECT Id,Number_of_Subscriptions__c,(Select Id from 
SBQQ__Subscriptions__r) from Contract where Id IN: contractIds]){
Contract conObj = new Contract ();
conObj.Id = con.Id;
conObj.Number_of_Subscriptions__c = con.SBQQ__Subscriptions__r.size();
lstContractsToUpdate.add(conObj);
}

UPDATE lstContractsToUpdate;
}    

The code is getting saved without any error.But the field on Contract called: Number of Subscription is not getting any updated.

9
  • 1
    Have you explored turning the lookup into an M/D and using "Rollup Summaries? Is that a possiblity? Feb 6, 2020 at 17:51
  • 1
    Also, there is a logical error. On Update, you're not touching trigger.new. If you update the ContractId on a given subcription, then the new contract will not get updated. Feb 6, 2020 at 17:53
  • Additionally, this might be better as an aggregate query like [SELECT COUNT(Id) FROM SBQQ__Subscription__c WHERE SBQQ__Contract__c IN :contractIds GROUP BY SBQQ__Contract__c] - this is more row query limits efficient. Also, the building of the contractIds array might be better to use s.SBQQ__Contract__c instead.
    – Phil W
    Feb 6, 2020 at 18:05
  • @sebastian I have modified the code .. then also its not working.
    – situ
    Feb 6, 2020 at 18:07
  • 1
    It's incredibly difficult to help you more without some details about your data and what you're doing with it Feb 6, 2020 at 18:09

1 Answer 1

2

You are pulling the ids that go into contractIds from a relationship on the trigger.new/old

 for(SBQQ__Subscription__c s:trigger.new){
     contractIds.add(s.SBQQ__Contract__r.id);
 }

Fields pulled from a parent relationship are not populated in trigger context variables.

So instead do:

for(SBQQ__Subscription__c s:trigger.new){
     contractIds.add(s.SBQQ__Contract__c);
 }
2
  • Bravo. Good catch! Feb 6, 2020 at 18:41
  • @eaeaoo it worked..!! thanks a lot..!!
    – situ
    Feb 7, 2020 at 4:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.