You need to sign in to do that
Don't have an account?
Need help to bulkify a simple trigger
I have a trigger that runs after a PO Number record is created. It finds the record's related Opportunity and updates the PO Number lookup field on the Opportunity with the PO Number that fired the trigger.
Everything works fine except that it's not bulkified. SOQL and DML in a for loop. I'm having difficulty understanding how to bulkify something like this. I know collections are needed but I'm not sure how to use them correctly.
Can anyone please help me understand a step by step process of how to bulkify something like this trigger? Any help is greatly appreciated.
trigger updateOppPoNumber on PO_Number__c (after insert) { for (PO_Number__c poNum : Trigger.new) { if (poNum.Id != null && poNum.Opportunity__c != null) { // Get related Opportunity List<Opportunity> opp = [ SELECT Id, PO_Number__c FROM Opportunity WHERE Id = :poNum.Opportunity__c LIMIT 1 ]; // Update related Opportunity with PO Number if (!opp.isEmpty()) { opp.get(0).PO_Number__c = poNum.Id; update opp; } } } }
All Answers
Thank you! I've decided to make some slight changes like changing Map<String, String> to Map<Id, Id> and one more null pointer exception before making the single update call. Are there any issues with this final code?
One more revision, my final code: