Programmatically manipulate a Node’s field value upon saving 

For a recent project we needed to automatically change a Node’s field value upon saving with a computed value. For an unrelated reason we needed this value to be in a regular text field, so using Computed Field was off the table.

It turned out to be really simple to accomlish with a minimal amount of custom code.

<?php
/*
 * Changes the value of field_marker to a string made up of the
 * Node's type and the value of it's category taxonomy term
 * Slashes will be replaced with deshes, spaces get removed
 * Must make sure that the following exists:
 *  - text field "field_marker"
 *  - node types "gesuch" and "angebot"
 *  - taxonomy reference field "field_category"
 */

// Helper function to keep our code
function save_marker_category($node) {
  if($node->type == 'gesuch' || $node->type == 'angebot') {

    $find = array('/', ' ');
    $replace = array('-', '');

    $category_object = taxonomy_term_load($node->field_category['und'][0]['tid']);
    $category =  trim(strtolower(str_replace($find, $replace, $category_object->name)));

    $type = $node->type;
    $node->field_marker['und'][0]['value'] = $type.'_'.$category;

    // Save the new value
    field_attach_update('node', $node);
  }
}

function MYMODULE_node_update($node) {
  save_marker_category($node);
}

function MYMODULE_node_insert($node) {
  save_marker_category($node);
}
Tags: 

Need a great new website or a helping hand with Drupal? Head over to www.klickreflex.de or contact me directly to see if we can work something out.