0
/*
 * Implements hook_node_presave()
 */

function custom_kca_node_presave($node) {
    drupal_set_message('DEBUG: PRESAVE Called');
    if ($node->type === 'product') {
        $node->field_product_short['und'][] = 'test';
    }
}

I created a custom textfield called field_product_short on the product Content Type.

A krumo check on $node after saving reveals $node->field_product_short to have the following:

field_product_short (Array, 1 element)
    und (Array, 1 element)
        0 (Array, 1 element)
            value (String, 1 characters ) t | (Callback) t();

?!? I'm setting it to a string in my HOOK. Why is it setting it to a value only of 't' with a callback t(); method? Shouldn't it just be reading:

field_product_short (Array, 1 element)
    und (Array, 1 element)
        0 (Array, 1 element)
            (String, 4 characters ) test

What am I doing wrong?

1 Answer 1

4

Your structure is wrong, you are missing the 'value' part. Something like this should work:

$node->field_product_short['und'][0]['value'] = 'test';

I'd recommend to explicitly use [0] instead of [], the first always writes the first field value while the second appends a new one (which is 0 if it is the first). Within it are the actual values of the field, which is, in case of a text field the mentioned 'value'. A term refernence would be tid, a node reference nid and so on.

The reason you are getting 't' is because the field structure is now a string where Drupal expects an array. Example:

$string = 'abc';
echo $string['value'];

This prints 'a', because only integers are supported when accessing strings like this which means 'value' is casted to a 0 and the first character of the $string is 'a'. Welcome to the strange world of PHP.

And another hint. The callback stuff is there because there also exists a function 't'. krumo doesn't know if something is a callback or not (as this is not possible to know in PHP), it simply checks if a function with the same name exists.

1
  • could this be applied when other node field value should be placed instead of 'test'. ex: $node->field_product_short['und'][0]['value'] = $node->field_some_other_field['und'][0]['value'];. Can we have access to $node->field_some_other_field here?
    – kiranking
    Apr 13, 2015 at 8:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.