Drupal - How to make a form required with states?
You will need to validate this yourself in a custom validate function.
Everything configured by #states happens 100% in the browser, everything that it does is not visible for Drupal when the form is submitted (for example, all invisible form field are submitted and validated in the same way if there were no #states).
You can use required like this:
'#states'=> [
'required' => [
':input[name="abroad_because[somecheckbox]"]' => ['checked' => TRUE],
],
],
Very similar to Felix Eve's answer only this is a snippet for inline element validation:
You call an element validate function the required element:
$form['element'] = array(
....
'#element_validate' => array(
0 => 'my_module_states_require_validate',
),
)
Then the validation function finds the required field and checks to see if it's has the correct form value which would reveal the field which needs to be required.
function my_module_states_require_validate($element, $form_state) {
$required_field_key = key($element['#states']['visible']);
$required_field = explode('"', $required_field_key);
if($form_state['values'][$required_field[1]] == $element['#states']['visible'][$required_field_key]['value']) {
if($form_state['values'][$element['#name']] == '') {
form_set_error($element['#name'], $element['#title'].' is required.');
}
}
}