function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
NongNong 

How to count Contracts under Opportunity?

Dear All,

 

The requirement i got is to alert message if user change status of Opportunity to 'Operational' and  no contract created under that Opportunit.

 

As user need to create at least one Contract before changing status Opportunity to 'Operational'

 

Could you please help me to provide some example source code to count total of created Contracts under Opportunity and how i can show validation message on the screen from APEX code.

 

Looking forward to your response and thank you very much in advance for you help.

 

Best Regards

Anong

kyle.tkyle.t

Hi,

  you need to query the contract table to get the count of contracts associated with the opportunity.  Something like this might bget you started.  you want to trigger on the opportunity, query the contract table for all contracts associated with the opportunity.  From there you need to match opportunites in the trigger to the opportunities in the query result...

 

Hopefully this points you in the right direction.

 

 

trigger preventOperationalOppWithoutContract on Opportunity (before insert, before update){
    AggregateResult[] groupedResults = [select COUNT(Opportunity__c), Opportunity__c from Contract where Opportunity__c IN : Trigger.new GROUP BY Opportunity__c];
    ...
}

 

 

NongNong

Hello,

 

Thank you very much for your help to give me the idea.

Finally i found it works on below coding.

 

trigger preventOperationalOppWithoutContract on Opportunity (after update){
    Integer countContract= [select COUNT() from Contract where Opportunity__c IN : Trigger.new ];
    
    If(countContract == 0)
    trigger.new[0].addError('Please create one contract when moving the opportunity stage to Operational');

}

kyle.tkyle.t

Hi nong, please understand that your solution above will work for single triggers, but if you are doing a bulk insert of opportunities, the first opportunity in each batch is going to fail since you are assigning an error to that record and any opportunities you are inserting won't have a contract yet.