0

I have a form that has a field with conditional validation. I mean if a certain radio button is checked, then the field need to be required. Please find below a code snippet of how I tried to solve it. Unfortunately, when I run this code, the field disappears, and when I comment out this logic, the field appears again.

I implemented the code from https://api.drupal.org/api/drupal/core!includes!common.inc/function/drupal_process_states/8.2.x.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYTHEME_form_user_register_form_alter(&$form, FormStateInterface $form_state) {

  $form['the_field'] = [
    '#states' => [
      // Only make the field 'the_field' as required when the 'field_of_type_radio' value is equal to '1'.
      'required' => [
        ':input[name="field_of_type_radio"]' => ['value' => '1'],
      ],
    ],
  ];

}

1 Answer 1

0
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYTHEME_form_user_register_form_alter(&$form, FormStateInterface $form_state) {
  // If your field is link field
  $form['the_field']['widget'][0]['uri']['#states'] = [
    // Only make the field 'the_field' as required when the 'field_of_type_radio' value is equal to '1'.
    'required' => [
      ':input[name="field_of_type_radio"]' => ['value' => '1'],
    ],
  ];
  // If your field is text field
  $form['the_field']['#states'] = [
    // Only make the field 'the_field' as required when the 'field_of_type_radio' value is equal to '1'.
    'required' => [
      ':input[name="field_of_type_radio"]' => ['value' => '1'],
    ],
  ];
}
1
  • Hey hey, could you please add some more explanation to your answer? Code-only answers are highly discouraged.
    – leymannx
    Commented May 23, 2018 at 11:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.