You need to sign in to do that
Don't have an account?
Paul Foley
Am I able to remove my Apex nested loops?
Hi All,
I'm putting together an invocable Apex method that gets called when an order is Activated.
The method loops around the products in the order (OrderItems) and create X number of Assets based on the quantity value of the order line.
This means I end up with a loop inside a loop. I'm not hitting limits yet, but am concerned that I could once we move the code to production.
Here's the offending code:
I'm putting together an invocable Apex method that gets called when an order is Activated.
The method loops around the products in the order (OrderItems) and create X number of Assets based on the quantity value of the order line.
This means I end up with a loop inside a loop. I'm not hitting limits yet, but am concerned that I could once we move the code to production.
Here's the offending code:
for(OrderItem prod : [select OrderItem.Product2.name, CurrencyIsoCode, id, Product2Id, Quantity, UnitPrice, OrderItem.Order.AccountId, OrderId from OrderItem where OrderId in : oids and OrderItem.Pricebookentry.product2.Is_Asset__c = true]){ for (integer i = 0; i < prod.Quantity; i++) { Asset a = new Asset(); a.name = prod.Product2.name; a.AccountId = prod.Order.AccountId; a.Price = prod.UnitPrice; a.Product2Id = prod.Product2Id; a.Quantity = 1; a.CurrencyIsoCode = prod.CurrencyIsoCode; a.Status = 'Purchased'; a.Order_Product__c = prod.id; newAssets.add(a); } } insert newAssets;
You would have problems if your insert statement was inside of a loop but you've avoided that so you should be safe.
All Answers
You would have problems if your insert statement was inside of a loop but you've avoided that so you should be safe.