[SalesForce] Restrict the number of children in lookup relationship

How do we restrict the number of children to 1 in a lookup relationship?

Best Answer

You would first need a way to know the count of children object your parent object has. If it were a master-detail relationship, you could use a rollup summary field for this.

You could change your lookup to a master detail, but if you don;t want to do that and keep it as a rollup, you have a few options.

  1. Use Rollup helper from the app exchange. Great tool that allows you to simulate rollup summaries on lookup relations. Check it out
  2. Try out the declarative rollup summary tool created by Andy Fawcett. Its an open source project he did to also allow you to simulate rollup summary fields on lookups. Check it out
  3. Write something yourself with Triggers or Batch classes (why reinvent the wheel?)

Once you have one of these created, then you will have a field on the parent that gives you the count of children. Then you just need to write a validation rule on the parent that ensures this count field in not greater than 1.

Count_Field__c > 1