2

I am trying to add some logic to auto select a node reference option on a select list on my content type. I am trying to set it with the following.

$form['field_my_field']['#default_value'][0]['nid'] = 5;

Where 5 is a nid. The value is set correctly in the form but when it is rendered to the page the option in the select list is not selected.

What am I doing wrong?

  • This looks like a good approach to me. Can you provide more context, eg. which hook you're using, maybe provide the whole hook; also can you say what if anything is selected instead? – Andy Jul 18 '11 at 14:05
2

CCK requires a little voodoo to alter values with a hook_form_alter(). You need to implement a special type: after_build, so put this code in a custom.module:

//Declare the callback for after_build for page node form
function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'page_node_form) {
    $form['#after_build'][] = 'custom_after_build';
  }
}

function custom_after_build($form, &$form_state) {
  //Set my node ref to 5
  $form['field_node']['nid']['nid']['#value'][0] = 5;
  //you can set more than one using 
  $form['field_node']['nid']['nid']['#value'][2] = 6;
  //have a look at the form after after_build
  dsm($form);
  return $form;
}

I adapted a previous answer of mine, but I have to admin that node reference is even more confusing ;)

1

According to docs you should:

'#default_value' => variable_get('field_my_field','5');

btw, maybe use javascript is the easiest way?

  • Do you have a link to the docs page you are looking at. – Rod Jul 18 '11 at 13:18
  • api.drupal.org/api/drupal/… – Codium Jul 18 '11 at 13:53
  • @drupality CCK elements don't always follow normal FAPI practices. – Andy Jul 18 '11 at 14:58
0

Assign a direct value to it. e.g.

$form['field_my_field']['#default_value'] = 5;
  • The option does not seem to be selected.... – Rod Jul 18 '11 at 12:57
  • @Shoaib I don't think this is ever right. – Andy Jul 18 '11 at 13:51

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.