I have a trigger which runs i will share a piece of code which is affecting the functionality
for(Pos_Item__c posItem:[SELECT Id,InProcess_Inventory_Stock__c FROM Pos_Item__c WHERE Id IN :posItemsWithInprocessInventory.keySet()])
{
if(posItem.InProcess_Inventory_Stock__c==null)
posItem.InProcess_Inventory_Stock__c=0;
posItem.InProcess_Inventory_Stock__c-=posItemsWithInprocessInventory.get(posItem.Id);
posItems.add(posItem);
}
I tried querying outside the for loop
List<Pos_Item__c> posItemsList = [SELECT Id, InProcess_Inventory_Stock__c FROM Pos_Item__c WHERE Id IN :posItemsWithInprocessInventory.keySet()];
for(Pos_Item__c posItem:posItemsList)
{
if(posItem.InProcess_Inventory_Stock__c==null)
posItem.InProcess_Inventory_Stock__c=0;
posItem.InProcess_Inventory_Stock__c-=posItemsWithInprocessInventory.get(posItem.Id);
posItems.add(posItem);
}
But still the same issue please help me understand how to overcome this issue
If i comment this piece of code everything is working fine.
But this part is very important
Thanks in advance
Tried using Map and List as well
The code you posted looks good, the for(Pos_Item__c posItem:[SELECT
syntax is legit. I think you have something outside this, another loop that calls this one over 100 times. Examine the debug log of your failed action, check if this SELECT...
appears in the log over and over… Or post a bigger snippet of the code?
There are static analysis tools like PMD or salesforce code scanner that might help identifying the loop.
There’s also chance you have recursion here (before update
trigger, updates something on “this” record, calls same trigger…), sometimes these are bit sneaky if you have trigger + flow for example.
If there’s no outer loop in this trigger / trigger handler itself… Generally what’s the outer code? This looks like some “mass reduce quantity on purchase order lines” – how is this called? 1 bulk update lineItems;
or an update statement in a loop?
1
1. Trigger Recursion: Is it possible that this trigger is firing more than once due to updates to the same records in the same transaction? If so, it might cause undesired changes to the InProcess_Inventory_Stock__c field, especially if the trigger is recursively updating Pos_Item__c records. You can add a recursion prevention mechanism to check if the trigger has already run for a particular record.
2. Order of Execution: Ensure that there are no other triggers, workflows, or processes that might be modifying InProcess_Inventory_Stock__c at the same time. This could cause unintended behavior.