Score:0

Validation for radio inputs don't work for me

il flag

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.

cn flag
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: https://www.drupal.org/project/examples
Jorn Reed avatar
il flag
@PatrickKenny no I did not know that haha. I'll take a look!
Score:0
il flag

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?

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.