0

I'm trying to set a default value in a template file for a radio button on my register form.

Female has value 0 and male has value 1. This is the code I use to set a default value:

    $form['field_personal_details']['und'][0]['field_gender']['und']['#default_value'] = '1';

I also tried

    $form['field_personal_details']['und'][0]['field_gender']['und']['#value'] = '1';

This should check the radio button as male, but it doesn't work. Whenever I set the default value to male through the UI it does work and I get the same outputs when I do a dpm.

What am I doing wrong?

1

Add direct user registration form alter and try to change "1" to 1.

function MYMODULE_form_user_register_form_alter(&$form, &$form_state,$form_id) 
{

  $form['field_gender']['und']['#default_value'] = 1;
    <---or ---> 
  $form['field_personal_details']['und'][0]['field_gender']['und']['#default_value'] = 1;

}
0

You need to use hook_form_alter() (or hook_form_FORM_ID_alter()) to alter forms:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'foo') {
    $form['field_personal_details'][LANGUAGE_NONE][0]['field_gender'][LANGUAGE_NONE]['#default_value'] = '1';
  }
}
2
  • Okay! How come I can change the value from text fields in my template though and not the radio buttons? May 9 '14 at 8:28
  • I have no idea :) I just know you're only supposed to alter forms with a form-alter hook - it's something to do with the elements already having been processed in drupal_get_form()
    – Clive
    May 9 '14 at 8:29

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.