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

  • Abhinav

    Member
    August 8, 2016 at 1:55 pm

    Hi Pranav,

    Test__c trigObj = trigger.newMap.get(Test.id);
    if(trigObj != null){
    trigObj.addError('Cloned record should not have the same period as that of Parent record');
    }

  • shariq

    Member
    July 17, 2017 at 1:48 pm

    Hi Pranav,

    Yes you can add error messages in triggers by using Salesforce trigger addError method.
    For Example - Sobject.addError('Error Messages');

    • This reply was modified 7 years, 5 months ago by  shariq.
  • Ratnakar

    Member
    April 10, 2018 at 2:22 pm

    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,'Enter Your error message here'));

  • PRANAV

    Member
    April 10, 2018 at 3:25 pm

    Hi Ratnakar,

    Whatever you are saying is not correct.

    The solution given by Abhinav is correct and helpful. And the issue resolves previously.

    I appreciate your response if it works for the same but the reply provided by you works for VF page only.

    Thanks

  • shariq

    Member
    September 20, 2018 at 7:00 pm

    Hi,

    Try this -

    obj.addError(‘error’);

    Hope this helps.

  • Parul

    Member
    September 20, 2018 at 7:11 pm

    Adding some points:

    If you want to print error message on particular field . you can use the following syntax
    FieldName.addError('Write error message');
    Display error message on visual force page include  <apex:pageMessages /> tag in vf page

    Thanks

  • 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

Log In to reply.

Popular Salesforce Blogs