0

I'm building a form with the drupal forms api. Validation works well for all my other fields. But I've started to try and work with radio buttons too now. It doesn't matter if I click on a radio option, the validation returns always 'color is required'.

// Form build method code
$form['birthdate'] = [
  '#type' => 'date',
  '#title' => $this->t('Your date of birth'),
  '#date_date_format' => 'd-m-Y',
];

$form['color_select'] = [
  '#type' => 'radios',
  '#title' => $this->t('Pick a color'),
  '#options' => [
    'blue' => $this->t('Blue'),
    'white' => $this->t('White'),
    'black' => $this->t('Black'),
    // 'other' => $this->t('Other'),
  ],
  '#attributes' => [
    'id' => 'color_select',
    'name' => 'field_color_select',
  ],
  '#states' => [
    'enabled' => [
      ':input[name="field_custom_color"]' => ['value' => ''],
    ],
  ],
];

// Form validator method code
if ($form_state->getValue('birthdate') == '') {
  $form_state->setErrorByName('birthdate', $this->t('Date of birth is required'));
}
if ($form_state->getValue('color_select') == '') {
  $form_state->setErrorByName('color_select', $this->t('Color is required'));
}

I thought that the getValue(name) and setErrorByname(name) have to the same as $form[name] =[]; to make it work, but for the radio buttons field, it doesn't.

2
  • Do you know of the Examples module? There's an example of radios (and many other parts of Form API) in the form_api_example submodule: drupal.org/project/examples Commented Nov 15, 2021 at 13:45
  • @PatrickKenny no I did not know that haha. I'll take a look!
    – Jorn Reed
    Commented Nov 15, 2021 at 13:47

1 Answer 1

0

I managed to get it working like this:

$form['color_select'] = [
  '#type' => 'radios',
  '#title' => $this->t('Pick a color'),
  '#options' => [
    'blue' => $this->t('Blue'),
    'white' => $this->t('White'),
    'black' => $this->t('Black'),
    // 'other' => $this->t('Other'),
  ],
  '#attributes' => [
    'id' => 'color_select',
    'name' => 'color_select',
  ],
  '#states' => [
    'checked' => [
      ':input[name="color_select"]' => [
        ['value' => 'blue'],
        'or',
        ['value' => 'white'],
        'or',
        ['value' => 'black'],
      ],
    ],
  ],
];

Although I'm not sure how it works now. Does it actually set the radio button on checked when the value is one of the given value ones?

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.