Floating a textfield next to a radio button in Drupal form


This can actually be done entirely with the Forms API. Here is an example:

 

// This will mimic the normal form element title as well as provide the group for our radio options.
$form[‘nations’] = array(
‘#type’ => ‘item’,
‘#title’ => t(‘Nationality’),
‘#description’ => t(‘<Enter your field description here.>’)
);
$form[‘nations’][‘american’] = array(
‘#type’ => ‘radio’,
‘#title’ => t(‘American’),
‘#default_value’ => 1,                    // If there is a default value, this should also be specified for each radio button.
‘#return_value’ => 1,
‘#parents’ => array(‘nations’),           // You must specify this for each radio button for them to act as a group.
‘#prefix’ => ‘<div>’  // The first radio button needs to make the style match a normal radios group.
);
$form[‘nations’][‘german’] = array(
‘#type’ => ‘radio’,
‘#title’ => t(‘German’),
‘#return_value’ => 2,
‘#default_value’ => 1,
‘#parents’ => array(‘nations’)
);
$form[‘nations’][‘other’] = array(
// The ‘container-inline’ class places elements next to each other, while the ‘form-item’ class provides the correct spacing between options.
‘#prefix’ => ‘<div>’,
‘#suffix’ => ‘</div>’
);
// By supplying the title here, instead of using the ‘#field_prefix’ property of the textfield, clicking the text will also select the radio button.
$form[‘nations’][‘other’][‘other_option’] = array(
‘#type’ => ‘radio’,
‘#title’ => t(‘Other:’),
‘#return_value’ => 3,
‘#default_value’ => 1,
‘#parents’ => array(‘nations’)
);
$form[‘nations’][‘other’][‘other_textfield’] = array(
‘#type’ => ‘textfield’,
‘#default_value’ => ”,
‘#size’ => 20,         // The default size is a bit large…
‘#suffix’ => ‘</div>’  // End of the “form-radios” style.
);

In your validation and/or submit callbacks, the selected radio option will then be in $form_state['values']['nations'] and the textfield value will be in $form_state['values']['other_textfield'].

With a little more work, you can change the example so that you don’t have to create each element manually .-)

Advertisements

, ,

  1. Leave a comment

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: