function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Phuc Nguyen 18Phuc Nguyen 18 

Apex Class to create child record when parent updated

Hello All,
I am trying to create an Ppex Class that creates a child record(asset__c) when the parent record(Warehouse__c) field(approved__c) is set to true. 
How do I make sure its bulkified so when the customer does a dataload there will not be an issue.
Thank you,
P
Best Answer chosen by Phuc Nguyen 18
David Zhu 🔥David Zhu 🔥
That would be AFTER UPDATE trigger. you can refer to the code below:

public static void CreateChildRecords(list<warehouse__c> warehouses)
{
       List<Id> warehouseIds = new List<Id>();
       for (warehouse__c warehouse: warehouses)
       {
             if (warehouse.approved__c)
             {
                   warehouseIds.add(warehouse.Id);
              }
        }    

     if (warehouseIds.size() > 0)
    {
       List<Asset__c> assets = new list<Asset__c>();     //SFDC has standard object Asset. are you sure they are not the same?

      for (Id id : warehouseIds)
     {
           Asset__c asset = new Asset__c();
          asset.warehouse__c = id;   // assume lookup or masterdetail field name is called warhouse__c on Asset__c object.
          asset. otherfields = .....
         assets.add(asset);
      }
       insert assets;
    }
}

All Answers

Agustin BAgustin B
HI Phuc, check this best practices link:https://developer.salesforce.com/page/Best_Practice%3A_Bulkify_Your_Code#:~:text=Explanation,records%20in%20that%20given%20batch.
You should use a for to iterate the list inserted/updated from dataloader. Inside that for you check the approved__c and if it is true then create the child and add it to a List so at the end after the for you just insert the list, avoiding every possible dml limit.

Good luck and if it helps please like and mark as correct.
David Zhu 🔥David Zhu 🔥
That would be AFTER UPDATE trigger. you can refer to the code below:

public static void CreateChildRecords(list<warehouse__c> warehouses)
{
       List<Id> warehouseIds = new List<Id>();
       for (warehouse__c warehouse: warehouses)
       {
             if (warehouse.approved__c)
             {
                   warehouseIds.add(warehouse.Id);
              }
        }    

     if (warehouseIds.size() > 0)
    {
       List<Asset__c> assets = new list<Asset__c>();     //SFDC has standard object Asset. are you sure they are not the same?

      for (Id id : warehouseIds)
     {
           Asset__c asset = new Asset__c();
          asset.warehouse__c = id;   // assume lookup or masterdetail field name is called warhouse__c on Asset__c object.
          asset. otherfields = .....
         assets.add(asset);
      }
       insert assets;
    }
}
This was selected as the best answer