A Drupal form radio buttons example (Drupal radios field)

Drupal radio buttons FAQ: How do I create an HTML radio button widget in a Drupal form?

Assuming that you're already comfortable with creating a Drupal form, you can create Drupal form radio buttons (technically a Drupal "radios" element) like this:

# an html radio button widget for a drupal 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['fourth_down'] = 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'],
);

This Drupal form element is declared to be a collection of radio buttons in this Drupal form type declaration:

  '#type' => 'radios',

This Drupal radio buttons form field ("radios") )definition renders an HTML radio buttons field that looks like this:

Drupal radio buttons example (Drupal radios element syntax)

(If you're not comfortable with creating a Drupal module or Drupal form, please see my first Drupal form example/tutorial.)

Note: I initially wrote this tutorial for Drupal 6, and I just tested it with Drupal 7, and it works there as well.

More Drupal radios form field options

You can add even more fields to your Drupal checkbox definition. The fields you can add are defined in the grid at this Drupal Form API reference page.

(There are over twenty Drupal radios field options you can use, so I don't want to list them all here.)

Drupal form radio buttons form example - Summary

I hope this Drupal form checkbox form example has been helpful. If you have any questions just leave a note in the Comments section below and I'll be glad to help (if I can).

Comments

Permalink

thanks for this - but

#default_value' => $options['punt'],

should be:

#default_value' => 'punt',

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.