I'm currently using hook_form_alter and $form['#after_build'] to try and set a term reference select list's default value to the first option in the list. I'm using the Reference Option Limit module in my content type, and even though the first item appears to be selected (because the field is set to Required), it's not. With help from the Devel module, I checked, and the #default_value is definitely empty. The closest I've gotten is with this:

function set_keywords_after_build($form, &$form_state) { 
    $keyword = $form['field_product_keyword']['und']['#options']; 
    $form['field_product_keyword']['und']['#default_value'] = $keyword; 
return $form; 

Looking at the page array, this will set the default value to:

#default_value (Array, 1 element) 
 - 13 (String, 19 characters ) KeywordName

where 13 is the tid of KeywordName.

Looking at another term reference field in the same form, it should look something like this:

#default_value (Array, 1 element)
 - 0 (String, 2 characters ) 38

Where 38 is the tid and 0 (I'm assuming) is the key?

  • Update: I scrapped the "#after_build" part and am now just using hook_form_alter, but I don't know what to add to the submit handler function. I should note that these nodes are being created by a Feeds import, and no manual editing or saving will be performed on them. function set_keywords_form_alter(&$form, &$form_state, $form_id) { if ($form_id == 'part_node_form') { $keyword = $form['field_product_keyword']['und']['#options']; $form['field_product_keyword']['und']['#default_value'][0] = $keyword; $form["#submit"][] = 'set_keywords_form_submit'; } } – McTwist Jan 10 '16 at 2:51
  • Your $keyword is a whole array, where you only want the '13' that is the index of the entry. $form['field_product_keyword']['und']['#default_value'][] = key($keyword); See get first key question. The empty bracket [] will be set to 0 and mimic that other term reference field. You could also use [0] – DeveloperWeeks Jan 19 '16 at 18:14

Your Answer

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

Browse other questions tagged or ask your own question.