Prady
Prady

Reputation: 11320

Prevent duplicate records in custom object

I have a custom object. There are combination of fields like month_c,Project_c,contact_c and role_c which determine the record as unique.

I can write a trigger on before insert to check if there are any records with the same combination already existing. The question i wanted to ask was

how can i make the insertion stop. once i find there is already an record then it should just not insert the record. it doesnt need to throw / show an error.

Thanks

Prady

Upvotes: 1

Views: 6855

Answers (3)

Matt Lacey
Matt Lacey

Reputation: 8255

Although others have answered this with better solutions (generally non-code solutions are more flexible for the end users of the system), the answer to stop a particular record from being inserted is to add an error to a field on that record.

For instance, if I was inserting accounts I might have something like this:

for(Account sAcct : trigger.new)
{
    if(sAcct.Name == 'DeniedAccount')
    {
        sAcct.Name.addError('This is a denied account.');
    }
}

Another alternative is to create a class extending Exception, and then throw a new instance of that exception class, this will prevent all of the records passed to the trigger from being processed as opposed to specific records.

Upvotes: 2

Matt K
Matt K

Reputation: 7337

A few days ago I found an incredibly useful and simple solution (in a ForceTree.com article) that prevented me from having to write a trigger. It allows you to combine fields to check for uniqueness using a workflow rule and a custom field.

Here's a walk-through: http://www.forcetree.com/2010/07/unique-field-combination-in-salesforce.html

Upvotes: 2

Jagular
Jagular

Reputation: 414

I have a similar situation in Salesforce. It is handled by creating a field that contains a value composed of all the values needed to guarantee uniqueness (in your case, month_c,Project_c,contact_c and role_c ). You then select the "Unique" checkbox for that field. Duplicates will now end up in the trash.

In my case, this new field is filled in (and pushed into Salesforce) by an external program. In your case, you'll need to fill in the value in your trigger. I think this is more efficient than doing SOQL queries in a trigger, but I have not done any checking to confirm this.

Upvotes: 1

Related Questions