Tricks or Treats: Using Roll Up Summaries & Validation Rules

There are times when using a roll up summary field in conjunction with a validation rule can prevent you from writing a Trigger with Apex. Say for instance we are building a recruiting application within Salesforce for a Haunted House. We will create two custom objects, Position__c and Applicant__c. Position__c will be the parent object (master) with Applicant__c being the child object (detail). Position__c can have many applicants, but only one Applicant__c can accept that position.

We have a few positions available.

However, we will focus on the Crazy Scientist position.

As you can see, there are 3 applicants for this position. Only one person can accept the position and we can enforce that one of two ways. We can write a before insert and before update Trigger that will pull down all of the other positions, verifying they are not accepted as well, or we can use a roll up summary and a validation rule. Let’s go with the latter of the two. No code, no unit tests, and easily modifiable. First we will need to create a roll up summary to count all Accepted applications for a position.

With this field set up, all we need to do now is set up a validation rule to ensure that the field we just set up can not exceed 1. This will force only one accepted applicant.


This will force an error to be thrown whenever an applicant is updated to be Accepted if there is already another Accepted applicant. Looking back at our Crazy Scientist example (I already updated John Doe to be Accepted), we can try to update Sam Doe to also Accept the position. This results in:

You can use this method in several different ways to avoid coding. Good luck!


Note: I tried my best to incorporate the halloween spirit into this post! I hope it wasn’t too bad!

Advertisement

Go to Smartblog Theme Options -> Ad Management to enter your ad code (300x250)

Comments are closed.