-2
trigger AccountDuplicateTrigger on Account (before insert)
{
 for(Account a:Trigger.new)
 {
 List<Account> acc=[Select id from Account where Name='a.Name' and Rating='a.Rating'];
 if(acc.size()>0)
 {
 acc.Name.addError('You Cannot Create the Duplicate Account');
 }
 }
 }
  • 3
    This looks like a good use case for Salesforce native duplicate management, not a trigger. I would recommend you invest some time in Trailhead modules like Bulk Apex Triggers. The logic of this trigger is incorrect in a number of ways, beyond the two major syntax errors - the incorrect Apex binding syntax and use of addError() against a record outside Trigger.new. – David Reed Jan 14 at 15:09
4

you are using the wrong way of variable binding. Is implemented by means of : colon symbol, that should be in your soql:

List<Account> acc=[Select id from Account where Name = :a.Name and Rating = :a.Rating];

by the way, you are using SOQL in a loop, that is very bad and is in opposition to trigger best-practices

Best Practice #2: Avoid SOQL Queries or DML statements inside FOR Loops

0

Adding an error to list is incorrect. so instead add error to the account record which is a here in our case a.addError('your error text here'); and if you want to add it to name field we can also do it by using a.Name.addError('your error text here');

Also,

  1. Using SOQL query in a loop is not a best practice
  2. Name is not a method or property of list so it's incorrect
  • 2
    Welcome to SFSE! Please take the tour and read How to Answer. I think this answer would be improved if you went into more detail about why your approach should work, and why the original approach didn't work. The object.field.addError('text') approach is valid. When I'm looking at a piece of code and wondering if it'll cause an error, my first stop is usually the official documentation. It's also a good idea to use anonymous apex (from the developer console) to execute the code in question (or similar code) to verify the problem / your solution. – Derek F Jan 15 at 16:01
  • The above approach is wrong. Adding an error to list is incorrect. so instead add error to the account record which is 'a' here in our case and if you want to add it to name field we can also do it by using a.Name.addError('your error text here'); – Sandeep Bollampally Jan 15 at 16:37
  • 1
    Forgot to mention, comments are best thought of as temporary. That additional information should be added to your answer by making an edit. – Derek F Jan 15 at 16:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.