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
alexMettealexMette 

Opportunity Contract Validation - referring to values in memory outside of trigger

Hello, I am trying to set up a rule that will prevent an opportunity from being changed to "Closed Won" unless it has a related Contract with a status of "Executed".

Our org has a custom contract object with a lookup to opportunity. 

We also have a process builder in place that fires when a contract is executed and automatically updates the related opportunity status to closed-won and updates the close date.

The reason for this is that we want to the opportunity to be closed as a result of its related contract being executed, and prevent it from being executed by sales people.

I created an Apex Class that is triggered on opportunity before update. It checks if the opportunity has a related contract and if the status of the contract is not "Executed", it throws an error. This works fine so far.

However, with the custom validation rule in place, the process builder cannot update the opportunity, so the whole transaction fails, and the contract can't be updated to executed.

As I understand it, this is because the contract hasn't been changed in the database until the whole process finishes.

I am new to Apex and development in general. Is there a way to access the value of the contract that is stored in memory in my opportunity trigger/class? Or, perhaps to create an exception to my rule that can be bypassed if the record update is triggered by a flow?

I'm definitely open to other solutions as well - but I'm curious if I've hit a limitation in trying to refer to a value of a record in memory vs. in the database that is not part of my trigger.