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
AlaaAlaa 

How to use a "before insert" apex trigger for validation?

Hi , am writing an apex trigger in which I need to validate the account name if already exist before insertion... so this trigger event will be "before insert" on "Account" object... my question is there is a way from the trigger to stop the insertion process and rase an error or warning to the user that this account name already exist?

 

Best Answer chosen by Admin (Salesforce Developers) 
Navatar_DbSupNavatar_DbSup

Hi,

 

You can try this

 

trigger CheckName on Account (before insert)
{
List<account> a1=[Select id from account where account.name=:trigger.new[0].name];
if(a1.size()>0)
{
trigger.new[0].name.addError('Account Name already Exist');
}

}

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved. 

All Answers

Navatar_DbSupNavatar_DbSup

Hi,

 

You can try this

 

trigger CheckName on Account (before insert)
{
List<account> a1=[Select id from account where account.name=:trigger.new[0].name];
if(a1.size()>0)
{
trigger.new[0].name.addError('Account Name already Exist');
}

}

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved. 

This was selected as the best answer
Devendra NataniDevendra Natani

Hello,

 

You can use the following trigger - 

 

trigger TR_Account on Account (before insert){

Set<String> accountNames = new Set<String>();
for (Account a : Trigger.New){
accountNames.add(a.name); 
}

List<Account> lstAccount = [select id from Account where name in : accountNames];

if (lstAccount.size() > 0){
Trigger.New[0].Name.addError('Account Name already exists');
}

}

 

Please let me know if there is any issue.

 

UVUV

You can follow the approach described in the link below to write your own trigger.make sure you bulkify your trigger. If suppose you are inserting records in bulk from the data loader or other external system then all records should be inserted except records with duplicate values. I dont know whether u want to insert all the records except duplicates or not but Just to clear you that In the above posted solutions you wont be able to insert a single record if there is any duplicates.. you must deal with sets and I would encourage you to go through link below-

 

http://developer.force.com/cookbook/recipe/preventing-duplicate-records-from-saving

http://boards.developerforce.com/t5/Apex-Code-Development/To-prevent-Duplicate-Records/td-p/189014

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_triggers_bulk_idioms.htm

 

 

goabhigogoabhigo

Hi, for such a small thing you need not write a trigger. But if there are other validations, updations included then you can. For triggers, you need to write test classes and get more than 75% code coverage in order to move into Production org.

 

So why don't you try simpler method? Create a unique text field (hide it from page layout), now using workflow field update copy the Account Name to this text field. Done!! Now if you try to create duplicate Account, you will see an error, with link to the existing Account. Better right?

AlaaAlaa

Thank you all for the help.

AlaaAlaa

How can I write a test for this apex trigger:

 

 

trigger CheckDupliacte on Account (before insert, before update)
{
String name=trigger.new[0].name;

List<account> a1=[Select id from account where account.name=:name];
if(a1.size()>0)
{
trigger.new[0].name.addError('Account Name already Exist');
}

UVUV

Let me tell you that in your trigger if you are inserting/updating records in bulk then-

1-if first record is a duplicate record then you wont be able to insert any rest of records regardless of whether they are duplicates are not.

2-If first record in not duplicate then it will insert/update all the records regardless of whether you have duplicates or not since you are checking with first record only.

 

To test your trigeer create a Account record with duplicate name in your test class and insert that to fire your trigger.

AlaaAlaa

Thanks Umesh.

salesforce sfdc 18salesforce sfdc 18
Trigger code for account name already exist

Trigger AccountInsert on Account(before insert) {

  for(Account a : Trigger.new) {

  List<Account> mynew = [select id, name from Account where name = :a.name];

 if(mynew.size()>0) {

a.name.addError('Account with name existing');

}
}
}

 
salesforce sfdc 18salesforce sfdc 18
Test class above Trigger:

@isTest

public class AccountInsert {
 
public static testmethod void testinsert() { 

string addError ;

string myname = 'raghavendra' ;

Account a2  = new Account(name=myname);

List<Account> x = [select name from Account where name=:myname];

if(x.size()<1) {

system.assertEquals(0,x.size());

insert a2;
}
else {
addError='Existing';
}
system.assertEquals('Existing',addError);
}
}



 
salesforce sfdc 18salesforce sfdc 18
Question:
when ever a record is created into account object.
before this new record is inserted into Account, delete all the contacts. 
records with this account name.

Answer:

Trigger  AccountInsert on Account (before insert) {

List<string> myname = new List<string> ();

for(Account a : Trigger.new) {

myname.add(a.name);

}

List<conatct> myconacts = [select id,name from contact where name=:myname];

delete myconacts;
}



@isTest

public class AcountInsert {

public static testmethod void testdelete() {

string myname = 'raghavendra';

Account a =new Account(name=myname);

contact con = new conatct(lastname='raghavendra');

insert con;
}

contact c=[select id,name from contact wher name=:myname];

if(c != null) {

system.assertEquals(c.name,a.name);

delete c;
}

insert a;
}