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
RobinHoodRobinHood 

To prevent Duplicate Records

Hi,

 

I'm trying to select a address from the database and displaying them in the Visual Force page by using a add button.

 

Say if I add

 

1870 Fair Oaks West Sunnyvale 94086 CA address to my list, I can again add the same address to my list which is causing duplicate records, how do I prevent this duplicate record from being added again ?

 

mtbclimbermtbclimber

It depends on where do you want your logic to exist that prevents the duplicate and the level of sophistication of your matching algorithm.

 

The first place to go is custom validation rules that are formula-based but if your matching logic isn't easily expressed in formulas (we do have a REGEX() function in formulas btw) and/or can't be, i.e. you need to look across multiple objects (tables) i.e. contact AND lead then you should drop to an Apex trigger to express your rule.

 

Doing duplicate prevention at the UI level, i.e. a Visualforce page, is almost never the right level but it can be done within the same controller using the same approach as the trigger if, in fact, you don't want this logic at the database level.

 

 

RobinHoodRobinHood

Hi Andrew,

 

Thanks for the clarification. I use only one object to retrieve the whole address and adding them to a list of places that I should visit.

 

Actually there no duplicate records in the objects. They are unique. But whenever I create a list of places to visit, I'm able to add same place more than once to my list. I want to avoid this. I think I should use trigger, I'm just learning how to create (use) trigger from the documentation. Thanks for your help. I'll get back if hit the wall somewhere.

 

Regards,

 

SR

Happy2HelpHappy2Help

Hi Robin

 

You are using list data type instead of it you should use "Set" data type.

A set is an unordered collection of primitives that do not contain any duplicate elements.

 

e.g. :-

// Suppose you have 10 records in your contact database having MailingCountry ( 4 records "USA" 2 records "UK" and 4 records "Australia"). In this case when you debug it with given code you fill find total 3 records , one record for each country . No duplicate records.

 

Set myadd = new Set();

for( contact c: [Select MailingCountry From Contact ])

{

   if(c.MailingCountry !=null)

       myadd.add(c.MailingCountry);

}


for( String s1: myadd)

  {

    system.debug('Addddddddddddd'+ s1 +'=======' + myadd.size());

   }

 

I think this will helps you.

 

Thanks

Michael

RobinHoodRobinHood

Hi Michael,

 

Thanks, I will try this out.

 

Regards,

 

SR