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
SFDC ROCKSFDC ROCK 

avoid duplicate field . code is running fine but I am able to find duplicate name ? please tell me what should i change in code.

class

//avoid dublicate record

public class dubli{

public static void avoid(list<trigger_object__C> ls)
{
set<string> stname=new set<string>();

for(trigger_object__c s:ls)
{
stname.add(s.city__c);

}
list<trigger_object__C> trlist =[select id,city__c from trigger_object__C where name in :stname];
map<string,trigger_object__C> maptr=new map<string,trigger_object__C>();
for(trigger_object__C s: trlist ){

maptr.put(s.city__c,s);
}

for(trigger_object__C s: ls){

if(maptr.get(s.city__C) != null){

s.adderror('dont insert duplicate name');
}

}
}
}


trigger:

trigger dup on trigger_object__c (before insert,before update) {

dubli.avoid(trigger.new);

}
Ramesh DRamesh D
@subodh
you are querying on name instead of city 
list<trigger_object__C> trlist =[select id,city__c from trigger_object__C where city__c in :stname];

I hope you find the above solution helpful. If it does mark as best answer to help others too.
Thanks,
Ramesh D
 
Tad Aalgaard 3Tad Aalgaard 3
Change 

if(maptr.get(s.city__C) != null)
to 
if(maptr.containsKey(s.city__c) && maptr.get(s.city__c).name == s.name)

also add name to the SOQL
list<trigger_object__C> trlist =[select id,name,city__c from trigger_object__C where name in :stname];