2

I am trying to set the default value of a select list field on a node add form. The field name attribute in the HTML of the form is:

field_state[und]

The ID of the add form is:

local-affiliate-node-form

I created a little module to try to do this. It just has this code in it:

function MODULENAME_form_alter(&$form, $form_state, $form_id) {
    if($form_id == 'local-affiliate-node-form'){
        $form['field_state']['und']['#value'] = 17;
    }
}

I enabled the module and cleared cache but it doesn't appear to work. I also tried these lines inside the IF statement:

$form['field_state']['und']['value'] = 17;
$form['field_state']['und']['value']['#value'] = 17;
$form['field_state']['und']['#default_value'] = 17;

In case you're wondering, I can't use the Drupal interface to set the default value because eventually that "17" will be dynamic, so it will change depending on what the user clicks and I will use a string in the URL in place of a static number.

Thanks for any help!

2
  • 2
    The form ID uses _, not -
    – Clive
    Commented Apr 10, 2014 at 18:04
  • Wow...rookie mistake! Thanks a lot Clive! If you post as a response I can mark it as the answer. Thanks again.
    – Micah
    Commented Apr 10, 2014 at 18:12

1 Answer 1

2

If you need "code" way you need set default value like this.

$form['field_name']['und']['#default_value'][0] = "1"

"1" - its number of element which you want set default.

I use that when i need set programaticaly default value for field which use term reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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