4

i am editing a form in drupal 7.1 and want to add a group of radios

    $form['yearofstudy']= array(
   '#title'=>'What is your year of study',
   '#type' => 'radios',
   '#options' => array(1=>'first year',2=>'second year',3=>'third year',4=>'fourth year',5=>'fifth year'),
   '#required' => true,
   '#default_value'=>array(1,0,0,0,0),
   );

The problem:
I intended the first option to be selected but this is what am getting enter image description here


Please help.

migrated from stackoverflow.com Oct 3 '11 at 11:57

This question came from our site for professional and enthusiast programmers.

7

A radio group can only have one radio selected. Did you try '1' as default value?

  • 1
    damn, you wont believe how long i have been trying to fix this :) – Dr Deo Oct 2 '11 at 11:47
  • 3
    yes, sunday was made to sleep. Might be a good reason for that – regilero Oct 2 '11 at 11:49
2

The working code to use:

$form['yearofstudy']= array(
  '#title'   => t('What is your year of study'),
  '#type'    => 'radios',
  '#options' => array(
     1 => t('first year'),
     2 => t('second year'),
     3 => t('third year'),
     4 => t('fourth year'),
     5 => t('fifth year')
  ),
  '#required'      => TRUE,
  '#default_value' => 1
);

p.s. also, according to drupal rules, we must use function t as in code above.

1

The definitive solution is here:

http://www.molecularsciences.org/drupal/making_your_checkboxes_preselected_in_edit_forms

The gist is to pass into #options an array of (name => name, name => name... ) and then the #default_value an array of (tid => name, tid => name...) for only the selected options and this gives us pre-selected options.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.