Prady
Prady

Reputation: 11320

Trigger to prevent duplicate record names in salesforce

I need to prevent duplicate names from been entered. This restriction needs to be imposed using a trigger. I want to know how i can restrict the DML operations from happening. Not sure of the usage of .addError in bulkified code.

 Set<string> Seta= new Set<string>();
 for(oj__c o:trigger.new)
 {
   Seta.add(c.name);
 }

 List<oj__c> listoj= new List<oj__c>();
 listoj=[select id from oj__c where name in :Seta]
 if listoj.size()>0
 trigger.new.adderror('Cannot have duplicate name');// i know this line is wrong. How can i stop the DML statement from excuting?

Upvotes: 2

Views: 6157

Answers (3)

superfell
superfell

Reputation: 19040

You code has a bug in that it won't spot dupes within the current batch, e.g. an API insert of 5 rows all the same name will go through.

An easier way to do this, is to just have your trigger copy the name field to a custom field, and then in the custom field definition set it to be unique.

Upvotes: 0

Prady
Prady

Reputation: 11320

A good reference to what i was looking for could be found here.

http://www.salesforce.com/docs/developer/cookbook/Content/apex_dedupe.htm

Upvotes: 2

Matt Lacey
Matt Lacey

Reputation: 8255

You can use addError with individual records which should then show against them on the report in dataloader, though if you want to stop everything where it is then you can also just throw an exception.

public class NamingException extends Exception {};

throw new NamingException('Found duplicate name');

Upvotes: 1

Related Questions