addError() Method in Salesforce Apex : Bijay Kumar

addError() Method in Salesforce Apex
by: Bijay Kumar
blow post content copied from  SalesForce FAQs
click here to view original post



### Summary of the Content The content explains the **addError() method** in Salesforce Apex, which is used to display custom error messages and prevent records from being saved when incorrect data is entered. While Salesforce has built-in validation rules, they may not suffice for complex scenarios, which is where **Apex** and the **addError() method** come into play. #### Key Points: 1. **Validation Rules vs. Apex**: Validation rules are useful for basic error checking, but Apex is needed for more complex conditions. 2. **addError() Method**: This method allows developers to throw custom error messages on records or specific fields, preventing any DML operation from occurring. - **Syntax**: `addError(fieldName, errorMsg)` - Example: `acc.addError('Name', 'Invalid Account Name');` 3. **Use Cases**: - **Preventing Data Changes**: You can stop users from changing critical fields, like account numbers or opportunity amounts, by checking values before saving. - **Avoiding Duplicates**: The method can be used to prevent the creation of duplicate records, such as accounts with the same phone number. #### Real-World Examples: - **Example 1**: Preventing changes to the account number in an account record. - **Example 2**: Restricting changes to the opportunity amount. - **Example 3**: Preventing account creation with duplicate phone numbers. ### Additional Context The **addError() method** is particularly useful in scenarios where data integrity is crucial, such as in financial systems or customer relationship management (CRM). By providing clear error messages, users can understand why their actions are being blocked, improving the overall user experience. ### Conclusion The addError() method is a powerful tool in Salesforce Apex for maintaining data quality and providing user feedback. It is essential for developers to understand how to implement this method effectively in various business scenarios. ### Hashtags for SEO #Salesforce #Apex #addError #ValidationRules #DataIntegrity #CRM #SalesforceDevelopment #Programming #ErrorHandling #CustomErrorMessages


We create validation rules in Salesforce to show errors on the record detail page. When a user enters incorrect data, the validation rule stops the save and displays an error message.

But when working with Apex, sometimes validation rules are not enough. For example, we need to use Apex code to check complex conditions or compare multiple records.

In Apex, we use the addError() method to stop the record from saving and show an error message. This works like a validation rule error, but gives you more control inside the code.

In this tutorial, we will learn about the addError() Method in Salesforce Apex. I will explain where and how to use addError() in real-time business scenarios using Apex code.

What is the addError() Method in Salesforce Apex?

The addError() method displays a custom error message in Salesforce Apex and prevents any DML operation from occurring. Another method, addError(fieldName, errorMsg), dynamically adds errors to fields of an sObject associated with the specified field name.

addError() is mainly used in Apex classes, Triggers, Validation logic, and Custom Business Rules to display custom error messages directly on specific fields or records.

Syntax: addError(fieldName, errorMsg)

Account acc = new Account( Name=’Test Account’ );
acc.addError( ‘Name’, ‘Invalid Account Name’ ); 

Here, we declare the account sObject. Then, we added an error message to the Name field using the addError() method with a custom message that we want to display.

Why Use addError() in Salesforce Apex?

We can use the addError() method for the following purpose:

  • It prevents incorrect data or values that do not match the defined condition.
  • We can display the custom error message to the user explaining why the save failed.
  • It works before the record is saved, so data quality is maintained.

Real-Time Examples to Use the addError() Method in Salesforce Apex

Now I will explain some real-time examples where we can use the addError() method to display a custom error message on the field or record page.

Example 1: Display Error Message at Bottom of Record Page

Let’s take an example: We have created an account record in the account object. If we try to change the account number field value of that existing account record, we need to throw an error message.

We checked the old and new account record IDs in the Apex trigger below. If the new account number is not equal to the old one, then that number is changed. So, here, we want to prevent that record from being saved.

For that, we added the addError() method, which displays error messages in Salesforce UI and prevents records from being saved. Provide the message that you want to display when the error occurs.

After that, save the Apex trigger code to activate it.

trigger PreventFieldChange on Account ( before update ) {
    
    for ( Account oldAcc : Trigger.Old ) {
          for ( Account newAcc : Trigger.New ) {           
                 if ( oldAcc.Id == newAcc.Id   && 
                        oldAcc.AccountNumber != newAcc.AccountNumber) { 
                               newAcc .addError ( 'You cannot change the Account Number.' );
         }
      }
   }
}

Navigate to the account object tab and open any existing account record in edit mode.

Use addError() in Salesforce Apex

Then, change the account number and enter a different value. Click the Save button to save changes.

Display Error Message in Salesforce Apex

As you click the save button, you will see the error message that you provided in the addError() method.

Display error on Record Page in Salesforce

In this way, we can use the addError() method in Salesforce Apex to display a custom error message at the Bottom of the record page.

Example 2: Display Error Message on the Field

For example, if you set the opportunity amount, you don’t want to change that amount by any other user, even if it is editable.

Suppose any user tries to change the opportunity amount and checks it against the new amount. If it does not match, then restrict the record from getting saved.

Now, to display the error message on the field, we need to provide the field API name before the addError() method.

trigger OppoTrigger on Opportunity (before update) {
    
    Map<Id, Opportunity> oppoMap = Trigger.oldMap;

        for ( Opportunity newOpp : Trigger.new ) {
                Opportunity oldOpp = oppoMap.get ( newOpp.Id );
                      if ( newOpp.Amount != oldOpp.Amount ) {
                            newOpp.Amount.addError ( 'Amount cannot be changed' );
                      }
           }
}

As you navigate to the opportunity record, you can see the number fields with the value of 4400.

addError() In Salesforce Apex

As I changed the value and tried to save the record, the error showed that we passed in the addError() method, and the record was not saved.

addError Apex Method

In this way, we can use the addError() method in Salesforce Apex to display a custom error message on the field.

Example 3: Prevent Saving Account with Duplicate Phone Number

For example, we need to ensure that we do not have two account records with the same phone number for security purposes. If the user provides a duplicate number, the error message should display, and the record should not be saved.

So, in Apex, we have created trigger code to stop users from creating or updating an account if another account already exists with the same phone number. It uses the addError() method to show an error message and prevent the record from being saved.

trigger addErrorMethod on Account (before insert, before update) {

    Set<String> incomingPhoneNumbers = new Set<String>();
    
    for (Account acc : Trigger.new) {
        if (acc.Phone != null) {
            incomingPhoneNumbers.add(acc.Phone);
        }
    }

    Map<String, Account> existingAccounts = new Map<String, Account>();

    for (Account acc : [SELECT Id, Phone FROM Account WHERE Phone IN :incomingPhoneNumbers]) {
                           existingAccounts.put(acc.Phone, acc);
                        }

    for (Account acc : Trigger.new) {
        if (acc.Phone != null && existingAccounts.containsKey(acc.Phone)) {
            acc.Phone.addError('An account with this phone number already exists.');
        }
    }
}

In the image below, we have one account record with a phone number value.

addError Method in Salesforce Apex

Now, when we try to create a new account with the same phone number as the existing account record and click the Save button, we get the error message we provided in the addError() method.

addError() Method in Salesforce Apex

In this way, we can prevent the users from creating an account if another account already exists with the same phone number by using the addError() method to show an error message and prevent the record from being saved.

Conclusion

I hope you have got an idea about the addError() Method in Salesforce Apex. I have explained where and how to use addError() in real-time business scenarios using Apex code.

You may like to read:

The post addError() Method in Salesforce Apex appeared first on SalesForce FAQs.


May 23, 2025 at 06:34PM
Click here for more details...

=============================
The original post is available in SalesForce FAQs by Bijay Kumar
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce