Monday, November 25, 2013

Drupal 7 - Presave a node (or doing custom validation and/or manipulation on field values)

I now have the simple specification that I have a text field in a Node which always needs to be uppercase, whatever the editor enters in the field. As a second specification I also want all spaces removed from the field values.
I could not find an example snippet to start up from, so I thought better publish this, maybe someone else will have  an easier live than me....

Field x: user may enter any character, but on saving the field all characters will be uppercased.
Field x: Also, alle whitespaces will be removed from the string

1. Create a module, in this example called customchr.
1. a Create info file

name = Custom CHR
description = Custum manipulations for the CHR site
package = Overboord
core = 7.x

2. Create module file customchr.module

function customchr_node_presave($node) {
  if ($node->type == 'publication') {
    // convert to uppercase
    // strip all whitespaces
    $node->field_publication_code[und][0][value]= preg_replace('/\s+/', '', $tempstring);


  1. I don't think it will work because when I am trying to get value of a field its not coming, here is output like var_dump output, how to get a value of var_dump output ?