Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add description to each radio button using drupal 7 forms api

Tags:

drupal-7

I got 4 radio buttons, and I would like to add a description to each one of them. Not just to the group of radio buttons.

This is my code:

     $form['bedrijfsfiche'] = array(
       '#type' => 'radios',
       '#title' => t('Keuze bedrijfsfiche'),
       '#options' => array('basis' => t('Basisbedrijfsfiche: €125'), 'Uitgebreid' =>          t('Uitgebreide bedrijfsfiche: €250'), 'gratis' => t('Gratis bedrijfsfiche'), 'contact' => t('Contacteer mij telefonisch voor meer uitleg')),
       '#access' => $admin,
    );

I can't seem to accomplish this, any help?

like image 267
dimitril Avatar asked Jan 23 '12 09:01

dimitril


2 Answers

By default, the individual radio buttons are not given a description when part of radios, but you should be able to add one yourself, based on what I see in the code.

  $descriptions = array(...); // descriptions, indexed by key

  foreach ($form['bedrijfsfiche']['#options'] as $key => $label) {
    $form['bedrijfsfiche'][$key]['#description'] = $descriptions[$key];
  }

Later on, when the radio buttons are expanded to separate buttons, it will make individual radio elements to these array [$key] locations, but it does it by appending, so anything there beforehand is preserved. That means you can add the descriptions, and yourself and they will stick around in the actual radio buttons.

like image 183
loganfsmyth Avatar answered Nov 04 '22 07:11

loganfsmyth


You need to add an additional key to the form array for each radio option. The key of the form array should be the key of the available option from #options, and the value should be an array containing the key of #description and the string you'd like to provide.

For a field example, the radio options are stored in $form['field_foo'][$lang]['#options']. If the contents of the #options array is ('buyer' => 'Buyer', 'seller' => 'Seller') then we add descriptions as follows.

// Since users and forms do not have language, use none.
$lang = LANGUAGE_NONE;

// Add descriptions to the radio buttons.
$form['field_foo'][$lang]['buyer'] = array(
  '#description' => t('Are you a sommelier, wine director, or beverage manager?'),
);
$form['field_foo'][$lang]['seller'] = array(
  '#description' => t('Are you a wine rep for a distributor, wholesaler, importer, or for a specific label?'),
);

It's a bit strange, but it works. :)

like image 24
jenlampton Avatar answered Nov 04 '22 06:11

jenlampton