Sunday, May 25, 2025

The formidable Formidable Forms - Which checkboxes are checked?



Helping someone close to me with their WordPress website, and more specifically Formidable Forms, it became apparent that the level of complexity with what they wanted was not as simple as we had hoped. 

Problem:

I needed to be able to determine which checkboxes the user had selected from a question. I didn't want to set up new forms and dynamically link data together (or however that works). I needed to know which product type was selected, and based on features (from checkboxes), compute a modified price for the product. 


Solution:

As I was thinking about the problem, it dawned on me that unique selection from a single number is not a new problem. We use bitwise calculation to determine permissions on file systems, so why wouldn't something like this work here as well?

Here is what I did. 

When you reference the field (group of checkboxes) using their field bracket notation "[123]" it returns the list of selections as a string with commas between each value selected. This is not a problem for JavaScript, but I wanted to solve the problem without writing JavaScript that would have listeners, etc. Also, in the checkboxes field, you can define custom values for each checkbox, and because every value has to be unique to the entire form, you generally preface the value with the option label. When they compute the numbers, they drop off the prefixes unless you specify you want the whole thing. 

In this case, I set up the checkboxes like this:

Option 1 (value: option1 - $1)

Option 2 (value: option1 - $2)

Option 3 (value: option1 - $4)

Option 4 (value: option1 - $8)

with the dollar amounts being base 2. (Ignore them as dollars amounts, that's purely for our logic - you will use the correct values later.) Then, I created an addition hidden field for each checkbox (called HasOption1, etc.) and added the calculation:

([123] % 2 >= 1) ? 1 : 0

To check the first option selection. The modulo 2 cuts off all the base 2 numbers above our target, and the the number "1" after it is checked as greater to or equal to our intended base 2 value (in this case 1) - which would come back as 1 if it is selected and 0 if it is not. 

For example, if we wanted to know if Option 3 was present, we would do this: 

([123] % 8 >= 4) ? 1 : 0

This is because Option 3 has a value of $4, and the value of Option 4 ($8) is too high. 

Later in the code, it was easy enough to reference the new hidden fields like Booleans to determine how to do more advanced calculations. 

If anything though, I realized there is probably a much better way to do forms on WordPress... I just likely won't be the one to build it. (Who knows? Maybe someone already did.)