in Web & Tech

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);
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Learn More)