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
Procurement ExecutiveProcurement Executive 

Can we use duplicate rule in trigger?

Can we use duplicate rule in trigger?
I have a requirement where I need to update contacts if duplicate contact gets created or added.
Agustin BAgustin B
HI, I dont know the condition you want to test but if it is the name for example you could do something like this inside the trigger:
trigger AccountDuplicate on Account (before insert)
{

	Set<String> setName = new Set<String>();
	For(Account acc : trigger.new)
	{
		setName.add(acc.name);
	}
	
	if(setName.size() > 0 )
	{
		List<Account> lstAccount = [select name ,id from account where name in :setName ];
		
		Map<String ,Account> mapNameWiseAccount = new Map<String,Account>();
		For(Account acc: lstAccount)
		{
			mapNameWiseAccount.put(acc.name ,acc);
		}
		
		For(Account acc : trigger.new)
		{
			if(mapNameWiseAccount.containsKey(acc.name))
			{
				acc.Name.addError('Name already Exist ');
			}
		}
		
	}
}

Instead of addError you can do what you want with the duplicated or existing record.
If it helps please like and mark as correct as it may help others.
DipthiDipthi
Here is another solution:

trigger EliminateDuplicateAcc on Account (before insert) {
   map<string,Account> AccNameMap = new map<string,Account>();
   List<string> AccNameList       = new List<string> ();
    for(Account Acc : Trigger.new){
        AccNameList.add(Acc.Name);
        AccNameMap.put(Acc.Name, Acc);
    }
   
List<Account> AccList = [Select Id,Name from Account where name=:AccNameList];
    If (AccList.size()>0){
        for (Account Acct : Trigger.new){
            if(AccNameMap.containsKey(Acct.Name)){
                Acct.adderror(Acct.Name + ' already exist!! Duplicates not allowed');
            }
        }
    }
  
}

If it helps, please like and mark as correct as it may help others.