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

Iteration loop based off value in custom field

I have 10 custom fields that I need to calculate values for. I will only be calculating a certain number of them based on the number in another custom field. For example if the value in number_of_parts__c is 6, I would only need to calculate the values for the first  6 custom fields and not the rest. How can I use the value in a custom field to run an iteration loop? Or is there another way to do this?





hmmm...   how's this....



List<String> fieldNames = new List<String>{'field1', 'field2', 'field2', 'field4', ...};

Opportunity opty = [select id, number_of_parts__c from Opportunity where id='xxxxxxxxxxxxxxx'];
Integer numOfParts = opty.number_of_parts__c.intValue();
for (Integer i=0; i<numOfParts; i++){
   String updateValue = '1';
   opty.put(fieldNames.get(i), updateValue);
update opty;




Sort of. The logic is more like this


Total_cost_1 = parts_month1 * cost_month1

Total_cost_2 = parts_month2 * cost_month2

Total_cost_3 = parts_month3 * cost_month3



Total_cost_10 = parts_month10 * cost_month10


but, I only need to do this up to the number in the number_of_parts__c field. So if the value is 5 then last calculation that will be run is Total_cost_5 = parts_month5 * cost_month5




I'm figuring there must be a way to increase the iteration after each calculation, but I'm just not sure of the proper code to do that.


ok..  so how about this:



Opportunity opty = [select id, number_of_parts__c, 
   parts_month1__c, cost_month1__c, total_cost_1__c,
   parts_month2__c, cost_month2__c, total_cost_2__c,
   parts_month3__c, cost_month3__c, total_cost_3__c,
   parts_month10__c, cost_month10__c, total_cost_10__c
   from Opportunity where id='xxxxxxxxxxxxxxx'];

Integer numOfParts = opty.number_of_parts__c.intValue();
for (Integer i=1; i<=numOfParts; i++){
   Double partsMonthValue = (Double) opty.get('parts_month'+i+'__c');
   Double costMonthValue = (Double) opty.get('cost_month'+i+'__c');

   opty.put('Total_cost_'+i+'__c', (partsMonthValue*costMonthValue) );
update opty;