Drupal Form Alter on a Node Reference Widget
boz — Mon, 07/18/2011 - 14:53
My latest battle with Drupal was overriding a select box that was a node reference. Intuitively I tried to simply update $form['#options'] with my array of custom data. No deal. After experimenting with about five ways to implement #after_build on both the form and the field, I realized that the type of a widget is something like 'nodereference_select' instead of just select. Switching the type back to 'select' allowed me to make the change. Wow. Lost a day to that one.
function mymodule_form_alter(&$form, $form_state, $form_id) {
if($form_id == 'mycontenttype_node_form') {
// setup array
$data = array();
// build your custom data
// i.e. write some code
// alter form
$form['field_myfield']['#type'] = 'select';
$form['field_myfield']['#options'] = $data;
}
} 
Okay, so I was completely
boz — Tue, 07/19/2011 - 13:54Okay, so I was completely wrong. I get errors submitting the form because of my hackery. Lesson learned. I admit I was wrong. Here is the correct code.
function mymodule_form_alter(&$form, $form_state, $form_id) { if($form_id == 'mycontenttype_node_form') { // setup array $data = array(); // build your custom data // i.e. write some code // alter form $form['field_myfield']['nid']['nid']['#options'] = $data; } }