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
kingsixkingsix 

Trigger for prevent the duplicate account name when lead convert to account

Hello, I wrote a trigger for prevent duplicate account name and group__C, it works well when I create a account in account page. But it shows a error info when I convert lead to account.

 

trigger test2 on Account (before insert, before update) {
   if (Trigger.new[0].Name != NULL)  {
       Account[] acc = [ select id from account WHERE name = :Trigger.new[0].Name and group__C=: trigger.new[0].group__C];
       if (acc.size() > 0) {
           Trigger.new[0].Name.addError('Name with Group already exists');
       }
   }
}

 

Anyone can help me? Thanks!

Best Answer chosen by Admin (Salesforce Developers) 
Alex_ConfigeroAlex_Configero

I'm assuming it's throwing an error because the lead does not have a group field, or it's not getting copied to the account upon conversion?

 

In that case you can change your condition to:

 

if (Trigger.new[0].Name != NULL && Trigger.new[0].Group__c != NULL )  {

 

And make the group field mandatory on the account page layout. This will let you create the account, then you can use a workflow to update the group field if you wish.

All Answers

Alex_ConfigeroAlex_Configero

I'm assuming it's throwing an error because the lead does not have a group field, or it's not getting copied to the account upon conversion?

 

In that case you can change your condition to:

 

if (Trigger.new[0].Name != NULL && Trigger.new[0].Group__c != NULL )  {

 

And make the group field mandatory on the account page layout. This will let you create the account, then you can use a workflow to update the group field if you wish.

This was selected as the best answer
MJ09MJ09

What would happen if your trigger was called with more than one Account, like if somebody uploaded a bunch of Accounts? Your trigger looks at only the first record, so it could allow duplicates to get through.

 

You can actually do this without Apex. Create a new Text field that's Unique and Case Sensitive. Then define a Workflow rule and action that concatenates the Name and Group values and stuffs the result into the new Text field.  After that, when somebody creates, updates, or even undeletes an Account, if that action would cause a duplicate value in that field, they'll get an error. 

kingsixkingsix

Great Thanks!