Skip to main content

How to use the Form Radios

DrupalVIP Support

Custom form sometimes need to have radio buttons, in order to create small selection options.
 

setting radios in a custom form:

# the options to display in our form radio buttons
$options = array(
  'punt' => t('Punt'),
  'field_goal' => t('Kick field goal'), 
  'run' => t('Run'),
  'pass' => t('Pass'),
);

$form['status'] = array(
  '#type' => 'radios',
  '#title' => t('What to do on fourth down'),
  '#options' => $options,
  '#description' => t('What would you like to do on fourth down?'),
  '#default_value' => $options['punt'],
);

 

Element properties may be set on single option items as follows.

$form['settings']['active'][0]['#description'] = $this->t('Description for the Closed option.');

 

On the submit callback method, here is how you get the radios selection:

$status = $form_state->getValue('status'); 

The status from the submit will hold the key of the selected option.

 

$form['settings']['active'] = [
    '#type' => 'radios',
    '#title' => $this->t('Poll status'),
    '#default_value' => 1,
    '#options' => [
        0 => $this->t('Closed'),
        1 => $this->t('Active'),
    ],
]