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
DS777DS777 

Before Insert Trigger question

I want to have a trigger on before insert ( if quantity is > then some condition error message is given).
I have written the trigger code in two ways, I need to know which is the correct or efficient way and why?
 
1st approach
-------------------
trigger ReceivedQtyCheck on Receipt__c (before insert) {
Set<ID> supplyId = new Set<ID>();
// Supply Order id
for (Receipt__c  receipts : Trigger.new)
        supplyId.add(receipts.SupplyOrder__c);
// Get the  Required Quantity and Received Quantity for the Supply Order
Map<Id, SupplyOrder__c> Supplies = new Map<Id, SupplyOrder__c> (
[select requiredQuantity__c, receivedQuantity__c from SupplyOrder__c where id in :supplyId]);

// Check the Receipt Quantity
for (Receipt__c receipts : Trigger.new)
        if (receipts.receivedQuantity__c > ((Supplies.get(receipts.SupplyOrder__c).requiredQuantity__c == null ? 0: Supplies.get(receipts.SupplyOrder__c).requiredQuantity__c)-
                                            (Supplies.get(receipts.SupplyOrder__c).receivedQuantity__c == null ? 0: Supplies.get(receipts.SupplyOrder__c).receivedQuantity__c)
                                           )
           )
        {
        receipts.addError('Received Quantity cannot be greater then Supply open quantity');
        }
}
 
2nd Approach
------------------
trigger ReceivedQuantityChk_01 on Receipt__c (before insert) {
for (Receipt__c receipts : Trigger.new) {
// get the Supply Order details
   SupplyOrder__c supplies = [select p.id, p.receivedQuantity__c, p.requiredQuantity__c from SupplyOrder__c p where p.id = :receipts.SupplyOrder__c Limit 1];
   try {  
// check the received quantity
  
      if (receipts.receivedQuantity__c > (supplies.requiredQuantity__c == null ? 0: supplies.requiredQuantity__c)
                                   -  (supplies.receivedQuantity__c == null ? 0: supplies.receivedQuantity__c)
         ) 
         {
         receipts.addError('Received Quantity cannot be greater then Supply open quantity');
         }
    }
    catch (Exception e) {
           System.debug(e.getMessage());
    }
 }
}
 
 
 
mikefmikef
The second approach you will run into query limits if the batch size is greater then 20, so for that reason alone the 1st approach is better.