Activity Forums Salesforce® Discussions How to add error message in a Salesforce Apex Trigger? Reply To: How to add error message in a Salesforce Apex Trigger?

  • shariq

    Member
    September 20, 2018 at 9:37 pm

    Hi,

    This is the code snippet -

    trigger AvoidDuplicateAccounts on Account (before insert, before delete)
    {
    Set<String> setAccountName = new Set<String>();
    for(Account objAccount: [Select Name from Account])
    setAccountName.add(objAccount.Name);
    for(Account objAccount: Trigger.new)
    {
    if(!setAccountName.contains(objAccount.Name))
    {
    setAccountName.add(objAccount.Name);
    }
    else
    {
    objAccount.Name.addError('Account with same name Exists');
    }
    }
    }

    Hope this helps