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
Nikhil SomvanshiNikhil Somvanshi 

Not able to throw error upon entering duplicate name field using triggers.

Hello Masters,

I am trying to write a trigger that is supposed to throw an error when a field Name is populated with a pre-existing value. Please have a look at my code below and advise. The code although saves successfully but doesn't work as desired.

Code Logic: 

if(trigger.IsInsert && trigger.IsUpdate)
{

List<Disasters__c> DisList = [select Id,Name from Disasters__c];

for (Disasters__c dis : Trigger.new)
{
    for (Disasters__c lis: DisList) 
    {
    
    if(lis.Name == dis.Name)
    {
    lis.Name.AddError('Name already exists. Try another name');
    }
}
 
Raj VakatiRaj Vakati
if(trigger.IsInsert && trigger.IsUpdate)
{

List<Disasters__c> DisList = [select Id,Name from Disasters__c];

 Set<String> names = new Set<String>();
	
    for (Disasters__c lis: DisList) 
    {
		
		names.add(lis.Name);
    }
	
	for (Disasters__c dis : Trigger.new)
	{
	   If(names.conatins(dis.Name)){
		dis.Name.AddError('Name already exists. Try another name');
		}

	}
}

 
Waqar Hussain SFWaqar Hussain SF
Hi Nikhil,

See below code which is updated code of @Raj.
 
if(trigger.IsInsert && trigger.IsUpdate)
{

 Set<String> NewNames = new Set<String>();
	
	for (Disasters__c dis : Trigger.new)
	{	
		NewNames.add(dis.Name);
    }
	
	List<Disasters__c> DisList = [select Id,Name from Disasters__c where Name IN : NewNames];
	Set<String> ExistingNames = new Set<String>();
    for (Disasters__c lis: DisList) 
    {
		
		ExistingNames.add(lis.Name);
    }
	
	for (Disasters__c dis : Trigger.new)
	{
	   If(!ExistingNames.add(dis.Name)){
		dis.Name.AddError('Name already exists. Try another name');
		}

	}
}

 
Nikhil SomvanshiNikhil Somvanshi
Much thanks Waqar and Raj for your help. May I please ask you if there is anything wrong if we go ahead and use a List<Sobject> (as i did) instead of using Set<String>.