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
AlanisticAlanistic 

Nested Ifs to calculate a value based on checkbox selection

What I'm looking for sounds quite easy but the more I think about it the more complicated it gets.

 

I have 4 checkboxes and I want to assign a percentage based on how many are checked.  So for example, if 1 is checked a field will be set to 25.  If 2 are checked then 50.  If 3 are checked then 75 and if all 4 are checked the field should be 100.

 

The checkboxes will be automatically set using a trigger when 4 specific actions are performed so what I need is a check to see how many boxes are checked and then provide the percentage.

 

I was hoping to use some kind of case statement, but it looks like there is no case statements in salesforce.  Would a series of IF statements be the way forward? 

 

I was thinking something along the lines of the below running each time the update trigger runs.

 

if 1 = true;{
    if 2 = true;{
        if 3 = true;{
             if 4 = true;{
             percent = 100;
             }else{ percent = 75;}
        }else{ percent = 50}
   }else{ percent = 25}
} else {percent = 0 }

 However in order to cover all the options each else would need to lead into another series of if statements and the if structure would become huge.

 

Does anyone have any suggestions on the best way forward?  All checkboxes are on the user object.

 

Or would I be better using a formula field and skip the APEX altogether?

 

Naidu PothiniNaidu Pothini
Percent = 0;

if(1)
{
	percent += 25; // Percent = 25;
	if(2)
	{
		percent += 25; // Percent = 50;
		if(3)
		{
			percent+ = 25;  // Percent = 75;
			if(4)
			{
				percent += 25; // percent = 100;
			}
		}
	}
}

 

So for example, if 1 is checked a field will be set to 25.  If 2 are checked then 50.  If 3 are checked then 75 and if all 4 are checked the field should be 100.

Percent = 0; Integer count = 0; if(1) { count++;} if(2) { count++;} if(3) { count++;} if(4) { count++;} percent = 25*count;

 I am not sure which one exactly suits your requirement but i guess these examples might help you...

 

gud luck...