Validate Opportunity Creation with Database Methods

Building error-resilient automations in Salesforce isn’t just about writing functional code—it’s about making sure your logic fails gracefully when things don’t go as expected. Whether it’s due to missing required fields, validation rule conflicts, or custom logic restrictions, handling insert errors in Apex triggers is essential for a smooth user experience.

This blog walks through a powerful example that demonstrates how to use Database.insert() with allOrNone=false, and how to apply addError() to surface the issue directly to the user when an insertion fails. The scenario involves creating an Opportunity record automatically whenever an Account is created—but with intelligent error handling if something goes wrong.

The trigger runs in the after insert context and leverages a Database.SaveResult[] to validate and report insert failures without crashing the entire transaction.

🧠 Why This Trigger Is Important


Automatically creating related records (like Opportunities when Accounts are created) is common in many Salesforce orgs. But what happens if:

  • A validation rule on Opportunity fails?

  • A required field isn’t filled correctly by your logic?

  • The user doesn’t have permission to create Opportunities?

If you use a standard insert statement, the entire transaction can fail—including the Account creation. That’s a bad user experience and can confuse your sales team.

Instead, using Database.insert() with allOrNone=false allows you to:

  • Attempt to insert all records individually

  • Skip failing records without rolling back successful ones

  • Capture error messages

  • Use addError() to attach the message directly to the source record, giving the user immediate, actionable feedback

This trigger is a great example of how to implement bulk-safe, user-friendly automation with built-in validation logic.

🔍 What This Blog Covers


  • How to use Database.insert() to handle individual record-level errors

  • Why allOrNone=false is important in bulk trigger operations

  • How to apply addError() to the Account object to notify the user of the related Opportunity failure

  • How to maintain clean, modular trigger code using a handler class

  • How to safeguard related record automation using Salesforce best practices

This is a must-know technique for developers working on scalable, real-world Salesforce implementations.

🎯 Real-World Use Cases for This Trigger


  • Auto-creating Opportunities, Contacts, or Cases when an Account is created

  • Provisioning records based on lead conversion or form submissions

  • Populating related records via API or batch inserts where failures must be captured individually

  • Partner portals where specific insert failures should not block the parent creation

  • Data migration or cleanup jobs with partial save logic

In any scenario where related record creation might fail due to data or permissions issues, this pattern ensures clarity and continuity.

👨‍💻 Developer & Admin Tips


Let’s break down the logic:

  • The trigger runs after Account creation

  • It loops through each Account and builds a corresponding Opportunity

  • Instead of using plain insert, it uses Database.insert(oppList, false)

  • This tells Salesforce: “Try to insert all Opportunities, but don’t rollback the others if some fail”

  • After insertion, it checks the SaveResult[] to identify which records failed

  • If there’s a failure, the error messages are collected and applied to the Account record using addError()

  • This surfaces the message directly to the user on the UI or in an API response

Benefits of this approach include:

  • Bulk-safe logic with proper indexing of errors to source records

  • Clear user feedback via inline error messages

  • Reduced risk of full transaction rollback

  • Faster troubleshooting and more professional user experience

Make sure to test this in both success and failure scenarios:

  • Try inserting valid and invalid Accounts in the same transaction

  • Trigger a validation error on Opportunity (e.g., missing a required custom field)

  • Watch how Accounts are saved but error messages appear for those linked to failed Opportunities

This trigger structure can be extended easily:

  • Add more complex logic to set default field values on Opportunities

  • Apply the same pattern to other objects like Contact, Task, or Case

  • Log failures in a custom object if needed for audit or monitoring

🎥 Watch the Implementation – YouTube Playlist


For a hands-on walkthrough, check out the Salesforce Makes Sense YouTube playlist. The video demo covers:

  • Setting up this trigger from scratch

  • Explanation of Database.insert() vs. standard insert

  • Live error generation and handling via addError()

  • Best practices for writing reusable and scalable trigger code

This visual aid helps developers and admins see how the logic behaves in real-time, especially in mixed-success scenarios.

Solution:

trigger AccountTrigger on Account (after insert) {
if(Trigger.isInsert){ if(Trigger.isAfter){
                              AccountTriggerHandler.createOpp(Trigger.new);
                 }
           }
}
public class AccountTriggerHandler{

            public static void createOpp(List<Account> accList){
                                  List<Opportunity> oppList= new List<Opportunity>();
                                  for(Account acc:accList){
                                  Opportunity opp= new Opportunity();
                                  opp.Name=acc.Name; opp.AccountId=acc.Id;
                                  opp.StageName=’Prospecting’; //
                                  opp.CloseDate=System.today();
                                  oppList.add(opp);
            }
             Database.SaveResult[] srList=
             DataBase.insert(oppList,false); for(Integer
             i=0;i<srList.size();i++){ if(!srList[i].isSuccess()){ String
             errors=”; for(DataBase.Error err:srList[i].getErrors()){
             errors=errors+err.getMessage();
                       }
                       accList[i].addError(errors); }
                }
        }
}

Want to Apply As Content Writer?

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart

Let's get you started!

Interested in writing Salesforce Content?

Fill in this form and we will get in touch with you :)