I am starting on Drupal 7 and the Forms API, and I'm making my first form.
What I want is to have a textfield that is #required => true and visible only if a checkbox is checked. If the checkbox is unchecked, the textfield must be invisible and not required.
It seems like a pretty basic case. Is there a way to do that without having to do it manually in the _validate function ?
Right now, I have a checkbox and a textfield with the #states parameter set to be visible only when the checkbox is checked. By itself, this is working fine.
My trouble comes when I try to set the #required parameter for the textfield. If I set it to true, then I cannot submit the form, even if the field is invisible.
So, I set the #required parameter of the textfield to a condition on the checkbox value, but checking or unchecking the checkbox does not make the red '*' appear, since the form is not rebuilt just by checking a checkbox.
I figured I needed to make an AJAX call to reload the field, so I added a #prefix and #suffix with a div on the textfield, and set an ajax call on the checkbox, returning the $form["mytextfield"] element to replace the div.