Drupal 6: Add/Remove field values from a Node Reference in a Content Type

Dev

Drupal 6: Add/Remove field values from a Node Reference in a Content Type

by Javod Khalaj

When creating a Content Type, one of your options is to create a field with a type: ‘Node reference’. Node references are a bit different than normal fields, in that they use other Content Type’s values to populate the field values.

This difference leads to some issues when trying to alter the Node Reference field on a Content Type form. What ends up happening, is that we do not have the ability to add/remove/alter values using the hook_form_alter() function directly. We end up needing a helper function for this. The code below is based on a select field:

function myModule_form_alter(&$form, &$form_state){
    if (arg(0) == 'node' && $form['form_id']['#value'] == 'myContentType_node_form') {
        // Replace our node reference field with the options we want using our helper
        $form['field_location']['#pre_render'] = array('helper_change_options');
    }
}

function helper_change_options($element) {
    $our_new_options = array(‘key’=>’value’, ‘key2’=>’value2’);

    // insert our new values into the element (which is a select field, options)
   $element ['nid']['nid']['#options'] = $our_new_options; return $element;
}

Please note that whatever options you change or add, those node key values DO need to exist in the Node Reference’s Content Type. Otherwise you are going to run into some problems.

More About the Author

Javod Khalaj

Experience Architect
Cohort Analysis in Tableau: User Retention Given Only Created and Last Seen Dates Cohorts have been the go-to analysis for user retention for a while now, and Tableau has a great article on how to go about creating ...
Use DreamObjects to Backup Your MySQL Database (PHP Script) DreamObjects is DreamHost’s public cloud storage offering. It’s analogous to Amazon’s S3 offering, but slightly cheaper. The nice thing ...

See more from this author →

Subscribe to our newsletter

  • I understand that InterWorks will use the data provided for the purpose of communication and the administration my request. InterWorks will never disclose or sell any personal data except where required to do so by law. Finally, I understand that future communications related topics and events may be sent from InterWorks, but I can opt-out at any time.
  • This field is for validation purposes and should be left unchanged.

InterWorks uses cookies to allow us to better understand how the site is used. By continuing to use this site, you consent to this policy. Review Policy OK

×

Interworks GmbH
Ratinger Straße 9
40213 Düsseldorf
Germany
Geschäftsführer: Mel Stephenson

Kontaktaufnahme: markus@interworks.eu
Telefon: +49 (0)211 5408 5301

Amtsgericht Düsseldorf HRB 79752
UstldNr: DE 313 353 072