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!

4 Responses to “Tricks or Treats: Using Roll Up Summaries & Validation Rules”

  1. 211
    December 5, 2013 at 1:45 am #

    this shows another way.
    so, a few lines of dup-check code VS two custom filed,
    which one is more efficient?

    • December 5, 2013 at 2:01 pm #

      I am not sure what your question is exactly, but I believe you are asking:

      “Why use validation rules w/ roll up summaries rather than some quick custom code?”


      When it comes to working with Salesforce, the key is to always utilize standard functionality first before introducing custom code. The reason for this is that their code will also be more heavily tested and typically much faster than anything you can write in Apex. On top of that, it offers more flexibility and it is something that can be turned off without a deploy.

      I hope that helps!

      • 211
        December 5, 2013 at 7:18 pm #

        Thank for the reply, i understand now.

        • January 21, 2014 at 1:02 pm #

          I thought I’d have to read a book for a diocevsry like this!

Leave a Reply to Carlye