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
Andrew DiBaccoAndrew DiBacco 

Duplicate Record Validation Rule Using Trigger

Hi all,

I'm stuck on creating a validation rule for a custom object. Bascially, the object is a form with a bunch of account lookup relationships and I need to make sure that the same account is not selected more than once. To make things a little more complicated, sometimes there will be several records (linked by the same custom parent object) and I also want to prevent duplicate accounts being selected across records of the same parent.

I can isolate all the accounts that I want to make sure aren't duplicated in the object records and send them to a list, but I don't know of an efficient way to actually pick up on a duplicate. Is there a method that already exists that will check for duplicates in a list? I don't need specific code, just the general idea of how I might do this.

Thanks,

Andrew
 
Best Answer chosen by Andrew DiBacco
Shashikant SharmaShashikant Sharma
Hi Andrew,

Here is the how you would require to develop this trigger :

1. This will be on before insert, beofre update events
2. Once any record is inserted or updated with an account lookup ( field that you dont want to be duplicate ). Go and find if there are any other records with the same account and do not have same parent account

So Your Query would be something like

Select Id From ObjectAPIName Where Account__c =: account Id From the inserted record And ParentId != Parent Id From the inserted record

if this query returns the result then use addError 
objInstance.addError( 'Duplicate Record');

You could start writing the trigger see various trigger post on this: http://forceschool.blogspot.in/search/label/Apex%20Triggers

Let me know if you face issues.
Thanks
Shashikant

 

All Answers

Shashikant SharmaShashikant Sharma
Hi Andrew,

Here is the how you would require to develop this trigger :

1. This will be on before insert, beofre update events
2. Once any record is inserted or updated with an account lookup ( field that you dont want to be duplicate ). Go and find if there are any other records with the same account and do not have same parent account

So Your Query would be something like

Select Id From ObjectAPIName Where Account__c =: account Id From the inserted record And ParentId != Parent Id From the inserted record

if this query returns the result then use addError 
objInstance.addError( 'Duplicate Record');

You could start writing the trigger see various trigger post on this: http://forceschool.blogspot.in/search/label/Apex%20Triggers

Let me know if you face issues.
Thanks
Shashikant

 
This was selected as the best answer
Andrew DiBaccoAndrew DiBacco
Thanks Shashikant, I got the trigger to work.
Shashikant SharmaShashikant Sharma
Glad that it worked for you :).

Thanks
Shashikant