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.
form_api_example
submodule: drupal.org/project/examples