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
EnryEnry 

Check if condition is satisfied for all related records

I'm writing a scheduled apex class and I would like to write a code to accomplish this:

 

check each account in the org and if an account has all opportunities with stage=”Cancelled” then set the checkbox named control =true on the account object.

 

For me it's difficult to check *if all* the opportunities have the stage ="Cancelled".

 

Please could you help me?

Thanks in advantage for any advice.

BR.

bob_buzzardbob_buzzard

I would look at using a rollup summary for this.  An account can have rollup summary fields that aggregate on the related opportunities.  In this case, you could create a formula field on the opportunity that has a value of 0 if the opportunity is cancelled, and 1 if the opportunity is in any other state.  Then have a roll up summary field on the account that gets the max of the formula field values - if this roll up summary field value is 0, that means every opportunity is cancelled, if not, it means at least one isn't.

 

You could also handle the checkbox by having a checkbox formula field on the account that is based on the value of the rollup summary.