Skip to main content

Apex Bulk Trigger Design Patterns

trigger SoqlTriggerBulk on Account(after update) {
    // Perform SOQL query once.  
    // Get the accounts and their related opportunities.
    List<Account> acctsWithOpps =
        [SELECT Id,(SELECT Id,Name,CloseDate FROM Opportunities)
         FROM Account WHERE Id IN :Trigger.New];

    // Iterate over the returned accounts  
    for(Account a : acctsWithOpps) {
        Opportunity[] relatedOpps = a.Opportunities;
        // Do some other processing
    }
}

trigger SoqlTriggerBulk on Account(after update) {
    // Perform SOQL query once.  
    // Get the related opportunities for the accounts in this trigger.
    List<Opportunity> relatedOpps = [SELECT Id,Name,CloseDate FROM Opportunity
        WHERE AccountId IN :Trigger.New];

    // Iterate over the related opportunities  
    for(Opportunity opp : relatedOpps) {
        // Do some other processing
    }
}

trigger SoqlTriggerBulk on Account(after update) {  
    // Perform SOQL query once.    
    // Get the related opportunities for the accounts in this trigger,
    // and iterate over those records.
    for(Opportunity opp : [SELECT Id,Name,CloseDate FROM Opportunity
        WHERE AccountId IN :Trigger.New]) {
  
        // Do some other processing
    }
}

Triggers execute on batches of 200 records at a time. So if 400 records cause a trigger to fire, the trigger fires twice, once for each 200 records. For this reason, you don’t get the benefit of SOQL for loop record batching in triggers, because triggers batch up records as well. The SOQL for loop is called twice in this example, but a standalone SOQL query would also be called twice. However, the SOQL for loop still looks more elegant than iterating over a collection variable!

trigger DmlTriggerNotBulk on Account(after update) {   
    // Get the related opportunities for the accounts in this trigger.        
    List<Opportunity> relatedOpps = [SELECT Id,Name,Probability FROM Opportunity
        WHERE AccountId IN :Trigger.New];          

    // Iterate over the related opportunities
    for(Opportunity opp : relatedOpps) {      
        // Update the description when probability is greater 
        // than 50% but less than 100% 
        if ((opp.Probability >= 50) && (opp.Probability < 100)) {
            opp.Description = 'New description for opportunity.';
            // Update once for each opportunity -- not efficient!
            update opp;
        }
    }    

}

trigger DmlTriggerBulk on Account(after update) {   
    // Get the related opportunities for the accounts in this trigger.        
    List<Opportunity> relatedOpps = [SELECT Id,Name,Probability FROM Opportunity
        WHERE AccountId IN :Trigger.New];
          
    List<Opportunity> oppsToUpdate = new List<Opportunity>();

    // Iterate over the related opportunities
    for(Opportunity opp : relatedOpps) {      
        // Update the description when probability is greater 
        // than 50% but less than 100% 
        if ((opp.Probability >= 50) && (opp.Probability < 100)) {
            opp.Description = 'New description for opportunity.';
            oppsToUpdate.add(opp);
        }
    }
    
    // Perform DML on a collection
    update oppsToUpdate;

}

trigger AddRelatedRecord on Account (after insert, after update) {
List<Opportunity> oppList = new List<Opportunity>();
    
    // Add an opportunity for each account if it doesn't already have one.
    // Iterate over accounts that are in this trigger but that don't have opportunities.
    for (Account a : [SELECT Id,Name FROM Account
                     WHERE Id IN :Trigger.New AND
                     Id NOT IN (SELECT AccountId FROM Opportunity)]) {
        // Add a default opportunity for this account
        oppList.add(new Opportunity(Name=a.Name + ' Opportunity',
                                   StageName='Prospecting',
                                   CloseDate=System.today().addMonths(1),
                                   AccountId=a.Id)); 
    }
    
    if (oppList.size() > 0) {
        insert oppList;
    }

}

trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {
List<Task> taskList = new List<Task>();
    
    // Assign a Task to an opportunity, whose StageName == 'Closed Won'.
    for (Opportunity o : Trigger.new) {
        if(o.StageName == 'Closed Won'){
            // Add a task to the opportunity
        taskList.add(new Task(Subject='Follow Up Test Task', WhatId=o.Id)); 
        }
    }
    
    if (taskList.size() > 0) {
        insert taskList;
    }

}

Comments

Popular posts from this blog

Visual Workflow

The benefits of Visual Workflow There are  certain benefits of using Visual Workflow. They are as follows: It allows you to create an automated business process using click not code. Visual Workflow does not require coding, and even if you do not know Apex code you can still develop business processes. Using screens, fields, and choices, you can implement complex business processes to make sure that your users are entering data in the right format. Through Visual Workflow, you can manipulate data for certain objects that are not available for the Workflow rule. For example, when a "contact role" is created or updated as primary for an opportunity then create a new task. It allows you to auto submit records for approval. You can post messages on Chatter. For example, if opportunity status gets Closed Won, post a message on Chatter group. It allows you to embed the Flow into the Visualforce page and using the Force.com Site you can expose it for ...

VisualForce Best Practices

Accessing component IDs When we refer Visualforce  components in JavaScript, the ID attribute plays a major role. Every Visualforce component has an ID attribute. The ID attribute must be specified to a particular component in order to refer to it in JavaScript and it is used to bind the two components together. When the page is rendered, this ID attribute is a part of DOM ID of the particular component. The ID attribute must be unique as well. The following best practices are applied for accessing component IDs: Use the  $Component  global variable  to simplify access. For an example, when we have an input field with  id="inputOne"  within a page block with  id="blockOne" , we can access the input field with the $Component.blockOne.inputOne  expression. No need to  specify an ID for a component you want to access if it is an ancestor or sibling to the $Component  variable in the Visualforce component's hierarchy. ...

Visualforce fundamentals

Visualforce  is a web development framework that enables developers to build sophisticated, custom user interfaces for mobile and desktop apps that can be hosted on the  Force.com  platform. You can use  Visualforce  to build apps with user interfaces that look like the standard interface provided by  Force.com , as well as your own completely custom interface. Visualforce  enables developers to extend  Salesforce ’s built-in features, replace them with new functionality, and build completely new apps. Use powerful built-in standard controller features, or write your own custom business logic in  Apex . You can build functionality for your own organization, or create apps for sale in the  AppExchange . Visualforce  app development is familiar to anyone who has built web apps. Developers create  Visualforce  pages by composing components, HTML, and optional styling elements.  Visualforce  can integrate with ...