+ Start a Discussion
RamakarryRamakarry 

duplicate prevention before triggers

Hi friends !
I have below snippet code which actually prevent duplicate contacts for an Account..but it's preventing every record to be insert...
trigger dupconprevention on Contact (Before Insert,Before Update) {
Map<String,Contact> lstb2 = new Map<String,Contact>();
for(Contact c:trigger.new){
if(lstb2.containskey(c.LastName) && lstb2.get(c.LastName).AccountId == c.AccountId){
contact cc = lstb2.get(c.LastName);
c.LastName.addError('Another contact with same Name exist');
}else
lstb2.put(c.LastName,c);
system.debug('my map'+lstb2);
}

for(Contact c:[select Id,AccountId,LastName from Contact where LastName In:lstb2.keyset()]){
Contact c2 = lstb2.get(c.LastName);
system.debug('Contact to be insert'+c2);
if((c.AccountId == c2.AccountId) && (c.LastName == c2.LastName)){
c2.LastName.addError('Already Exist');
}
}
SandhyaSandhya (Salesforce Developers) 
Hi Ramakarry,

Please see below code.
trigger ContactDuplicateTrigger on Contact (before insert) {
for (Contact c : Trigger.new){
Contact[] contacts= [select id from Contact where 
    (FirstName = :c.FirstName and LastName = :c.LastName) and 
    (Phone=:c.Phone or MobilePhone=:c.MobilePhone or HomePhone=:c.HomePhone or OtherPhone=:c.OtherPhone or Home_Phone_2__c=:c.Home_Phone_2__c 
    or Email = :c.Email)];
if (contacts.size() > 0) {
c.LastName.addError('Contact cannot be created - Contact already exists with the same email or name-phone combination.');
} 
}
}


Please accept my solution as Best Answer if my reply was helpful. It will make it available for other as the proper solution. If you felt I went above and beyond, you can give me kudos.
 
Thanks and Regards
Sandhya