I've written the below trigger but get this error:

Compile Error: line 5:20 no viable alternative at character '"' at line 5 column 20

What's wrong with my code? How can I fix it?

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";
            acc.Name.addError('You Cannot Create the Duplicate Account');

You can only use single quotes to declare strings, not double quotes. But in this case, you actually need square brackets ([]) to perform your query.

List<Account> acc = [SELECT Id FROM Account WHERE Name=:a.Name AND Rating=:a.Rating];

That will get your code to compile. You still need to bulkify, however. You might consider just using out of the box Duplicate Management, which doesn't require code. Another option that will allow you to implement this validation without code is to create a unique text field and concatenate Name and Rating into it. You'll have to data load to backfill already existing records, however.

One other compile error you will hit is that you are trying to reference acc.Name instead of a.Name, where acc is a List<Account>, which does not have a Name attribute. Instead, you need to add the error to the Name field on the single Account record that is your loop variable (a).

  • That did work. thanks! but I have encountered a new error called Error: Initial term of field expression must be a concrete SObject: List<Account> at line 8 column 2. Any idea why? – user31302 Feb 27 '17 at 19:35
  • @SFDCLearner You need to add the error to the loop variable, not the list. See my updated answer. – Adrian Larson Feb 27 '17 at 19:37

Your Answer

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