You need to sign in to do that
Don't have an account?

Hi All,I am new to coding .I have written a trigger to prevent duplicate account ,my trigger is :
trigger prevent_duplicate_account on Account (before insert) {
map<id,Account> mapAcc = new map<id,Account>([Select id,name,rating from Account ]);
for(Account a : Trigger.new)
{
if(a.Name==mapAcc.get(a.id).name && a.rating==mapAcc.get(a.id).rating)
a.adderror('you cant add duplicate account');
}
}
I have already an account with name as IGA ,i am updating this account with rating =warm ,it is preventing to save record .since I have used && condition ,if both are true then only it should save the record to save . Also If i am creating a record with name as IGA and rating different from the previous one than also I am getting error .What can be done please help
Thanks in advance!!
map<id,Account> mapAcc = new map<id,Account>([Select id,name,rating from Account ]);
for(Account a : Trigger.new)
{
if(a.Name==mapAcc.get(a.id).name && a.rating==mapAcc.get(a.id).rating)
a.adderror('you cant add duplicate account');
}
}
I have already an account with name as IGA ,i am updating this account with rating =warm ,it is preventing to save record .since I have used && condition ,if both are true then only it should save the record to save . Also If i am creating a record with name as IGA and rating different from the previous one than also I am getting error .What can be done please help
Thanks in advance!!
You need to use before Update event trigger as well as.
Trigger preven_Duplicat_account on Account(before insert, before update)
As per your above trigger when ever the both scenarios are true it will throughs the error. Insted of above code you can use below peace of code.
trigger AccountDuplicateTrigger on Account (before insert,before update) { for(Account a:Trigger.new) { List<Account> acc=[select ID from account where Name=:a.Name and Rating=:a.rating]; if(acc.size()>0) { a.adderror('You cannot create a dulplicate account'); } } }
Let us know if this will help you
if(listacc !=null){
for(Account a1 : listacc)
{
string key = a1.name +'-'+ a1.rating;
mapacc.put(key,a1);
}}