+ Start a Discussion
srikanth j 24srikanth j 24 

Account Duplicate Trigger

Hi guys,
I have trigger scenario like  when i try to create account if already exists that account name i want to show error message like duplicate account not allowed
can anyone give me a solution for this.if could send me code.
Thanks in Adv 
sfdcMonkey.comsfdcMonkey.com
hi srlkanth
try this trigger
trigger DuplicateLead on account(before insert,before update)
{
 
         Set<string> name= new Set<string>();
   
      
        
         for(account acc : Trigger.new)
         {
           name.add(acc.name);
         }

       
       List<account> duplicateaccountList = [Select name From account where name = :name];

       Set<string > duplicateaccIds= new Set<string >();

       for(account dup: duplicateaccountList )
       {
         duplicateaccIds.add(dup.name);
       }

       for(account a : Trigger.new)
       {
            if(a.name!=null)
            {
               if(duplicateaccIds.contains(a.name))
               {
                 a.addError('Record already exist with same Name');
               }
            
            }
       }
}
Thanks
Mark it best answer if it helps you so it make proper solution for others :)
Prateek Singh SengarPrateek Singh Sengar
Hi Srikanth,
You dont need a trigger for this. Simply create another custom field of type text with unique attribute. Then create a workflow with field update to copy the account name to this custom field. 
Hope this helps.
Amit Chaudhary 8Amit Chaudhary 8
Please try below code
 
trigger DuplicateAccount on account(before insert,before update)
{

	Set<string> Setname= new Set<string>();
	for(account acc : Trigger.new)
	{
		Setname.add(acc.name);
	}

       
	List<account> duplicateaccountList = [Select name From account where name in :Setname ];
	
	Map<string,Account> duplicateaccIds= new Map<string,Account>();

	for(account dup: duplicateaccountList )
	{
		duplicateaccIds.add(dup.name,dup);
	}

	for(account a : Trigger.new)
	{
		if(a.name!=null)
		{
			if(duplicateaccIds.containsKey(a.name))
			{
				a.addError('Record already exist with same Name');
			}
		}
	}
	
}
Please check below post for use of collection
1) http://amitsalesforce.blogspot.com/2016/09/collection-in-salesforce-example-using.html

Please check below post to learn Trigger
1) http://amitsalesforce.blogspot.com/search/label/Trigger

1) One Trigger Per Object
A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts

2) Logic-less Triggers
If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org.

3) Context-Specific Handler Methods
Create context-specific handler methods in Trigger handlers


4) Bulkify your Code
Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

5) Avoid SOQL Queries or DML statements inside FOR Loops
An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

6) Using Collections, Streamlining Queries, and Efficient For Loops
It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

7) Querying Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore

8) Use @future Appropriately
It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

9) Avoid Hardcoding IDs
When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail
raj_sfdccraj_sfdcc
Hi ,
Below post can be used to avoid Duplicate Fields by using trigger :

Here i have used Author object and Email field for my requirement .Please use your Sobject and field according to your requirement in the place of Email
trigger DemoTrigger on Author__c (before insert,before update) {
    List<Author__c> accList=new List<Author__c>([select Author_Email__c from Author__c]);
    map<String,Author__c> accmap=new map<String,Author__c>();
    for(Author__c acc:accList){
        accmap.put(acc.Author_Email__c,acc);
    }
    //For Insert Operation
    if(Trigger.isinsert&&Trigger.isbefore){
        for(Author__c acc:Trigger.new){
            if(accmap.get(acc.Author_Email__c)!=null){
                acc.adderror('Email already exists');
            }
        }
    }
    //For Update Operation
    if(Trigger.isupdate&&Trigger.isbefore){
        for(Author__c acc:Trigger.new){
            if((Trigger.oldmap.get(acc.id).Author_Email__c!=acc.Author_Email__c)&&                                           (accmap.get(acc.Author_Email__c)!=null)){
                acc.adderror('Email already exists');
            }
        }
    }

}


Please find the below post further information:

Avoid Duplicate for Insert Operation By Using Apex Trigger (https://salessforcehacks.blogspot.com/2019/12/avoid-duplicate-fields-using-apex.html)  
And the below Post explaines how to avoid Duplicate Fields by updating the above code :

Avoid Duplicates for both insert and Update Operation (https://salessforcehacks.blogspot.com/2019/12/avoid-duplicate-fields-using-apex_21.html)  

I have created insert and update operation seperately  to make you understand Clearly.

Please let me know if you require any further information
smriti sharan19smriti sharan19

WAY1
trigger AccountDuplicateCheckTrigger on Account (before insert) {
       //Preparing Account names in Set from trigger.new

        Set<String> nameSet = new Set<String>();

        for(Account acc : trigger.new){

            nameSet.add(acc.name);        

        }

        // getting the list of accounts in database  with the account name we entered ( trigger.new)
        
        List<Account> accList = new List<Account>([select id,name from Account where name in: nameSet]);

        for(Account a : trigger.new){

            if(accList.size() > 0 )
                a.addError('Account already exists in your Organization with name '+a.name);

        }

}
WAY2
--
Check Using null condition
trigger DemoTrigger on Account(before insert,before update) {
    List<Account> accList=new List<Account>([select id,name from Account]);
    map<String,Account> accmap=new map<String,Account>();
    for(Account acc:accList){
        accmap.put(acc.Name,acc);
    }
 
        for(Account acc:Trigger.new){
            if(accmap.get(acc.Name)!=null){
                acc.adderror('Name already exists');
            }
        }
    }
WAY3
----
Check using containsKey condition
trigger DemoTrigger on Account(before insert,before update) {
    List<Account> accList=new List<Account>([select id,name from Account]);
    map<String,Account> duplicateMap=new map<String,Account>();

    //get old records 
    for(Account acc:accList){
        duplicateMap.put(acc.Name,acc);
    }
    //compare old records with records in trigger.new
        for(Account acc:Trigger.new){
          if(duplicateMap.containsKey(acc.Name)){
                acc.adderror('Name already exists');
            }
        }
    }
    
http:www.sfdcamplified.com (http://www.sfdcamplified.com)