dimitril
dimitril

Reputation: 393

Add description to each radio button using drupal 7 forms api

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?

Upvotes: 6

Views: 4080

Answers (2)

jenlampton
jenlampton

Reputation: 312

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. :)

Upvotes: 4

loganfsmyth
loganfsmyth

Reputation: 161567

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.

Upvotes: 9

Related Questions