0

Whenever an Order is inserted with Pricebook and Status of 'Activated', create a child Order_Pricebook__c record.

trigger createorderpricebook on Order (before update) 
{
    for(Order ce:trigger.new)
    {
        if(ce.status =='Activated')
        {
        order cf = [select id,pricebook2.id from order where id=:ce.id];
        Order_Pricebook__c gh = new Order_Pricebook__c();
        gh.name= 'ela';
        gh.Order__c = cf.id;
        gh.Price_Book__c = cf.pricebook2.id;
        insert gh;
        }

     }
}

How can I rewrite this Apex Trigger to handle bulk operations?

5

You should really look up handler patterns while you're learning how to write an Apex Trigger. See below for more detail.

Just pull the query and dml out of the loop. Actually to get the prior state of a record, you do not need to query, so just remove it entirely. Just get them from the oldMap. In this case you can even just loop over it directly.

List<Order_Pricebook__c> junctions = new List<Order_Pricebook__c>();
for (Order record : trigger.old)
    junctions.add(new Order_Pricebook__c(
        Order__c=record.Id, Price_Book__c = record.Pricebook2Id
    ));
insert junctions;

Trigger Handlers

The Force.com platform supports attaching any number of triggers to an object, but there is no guaranteed order of execution, and multiple trigger instances often query the same set of data, which can cause performance and governor headaches.

To avoid these problems, and others, an accepted best practice is to delegate trigger handling to a second class, so that there is one trigger handler per object.

Resources

3

Few things to be noted while bulkifing code,

  1. Do not query record or do DML operation in the for loop.
  2. Avoid unnecessary queries.
  3. Use list while inserting records instead of inserting records this applies to delete and insert also.

Your trigger's bulkified version,

trigger createorderpricebook on Order (after update) {
    List<Order_Pricebook__c> orderPriceBookList = new List<Order_Pricebook__c>();

    for(Order ce:trigger.new) {
        if(ce.status =='Activated'){
            Order_Pricebook__c gh = new Order_Pricebook__c();
            gh.name= 'ela';
            gh.Order__c = ce.id;
            gh.Price_Book__c = ce.pricebook2Id;
            orderPriceBookList.add(gh);
        }
    }

    insert orderPriceBookList;

}
  • 2
    Please do not just post a code dump. An answer is of much greater value when it contains an explanation. – Adrian Larson Jul 19 '16 at 15:45
  • 1
    Nice explanation! +1 – Adrian Larson Jul 19 '16 at 15:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy