Activity › Forums › Salesforce® Discussions › How to add error message in a Salesforce Apex Trigger?
-
How to add error message in a Salesforce Apex Trigger?
Posted by PRANAV on August 8, 2016 at 1:45 PMHi All,
How to add error message in apex trigger ?
Thanks
shariq replied 7 years, 8 months ago 5 Members · 7 Replies -
7 Replies
-
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’);
} - [adinserter block='9']
-
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,’Enter Your error message here’));
-
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
-
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 pageThanks
-
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.