in trigger apex ~ read.

Using Triggers as advanced validation rules in Salesforce

Today I wanted to cover an interesting usage of triggers.

Salesforce has out-of-the-box validation rules. By using point-and-click techniques from the Setup page you can create some powerful validation logic. However, these rules can only go so far and don't allow for very complex logic. By using the sObject.AddError() method in a trigger, you can prevent an object creation or update from happening. This allows you to effectively use a trigger as a more powerful validation mechanism than validation rules.

Let's use an example. Assume that our customers wants to make sure that any opportunity that goes beyond prospecting stage must have an associated contact role. As far as I know, there is no simple way to do this with validation rules (but if you find a way to do so, please get in touch!). Let's see how we would do this with a trigger.

Step 1: Create validation logic

First, we'll encapsulate the validation logic in a separate class (to avoid making the trigger too big and difficult to read):

We can call this validation logic by calling the ValidateOpportunity() method. If the Opportunity is in qualification or prospecting stages, it will validate true; otherwise, it will check that it has any contact role associated to it, and will validate to false if it doesn't.

Step 2: Create the trigger

All our trigger needs to do is call the validation, and reject the transaction if the validation fails:

There you go. Nice and easy trigger. By calling .AddError(), any opportunity DML will fail if it fails the validation criteria we created with our validation class. We can see this in action below:

Opportunity fails validation

Bonus! Create unit tests

Since we are nice Salesforce developers, we want to have test coverage for our validation (NB: It is actually recommended that you write your tests before your class, but that's a more advanced topic for another day):

We can see that our test code is actually longer than our "production" code. This is quite frequent! There are many cases to test.

Conclusion

We've seen how a trigger using the .AddError() method can work as a validation rule. This kind of validation logic can be much more complex than with validation rules and adapt to more demanding business needs.