Changing field values from a preprocess function: figuring it out

  • Figuring this out took a while, as recorded at http://drupalbin.com/17844 for the onlookers and assisters in IRC.

    Functions and API docs read over in the process included theme_field(), hook_preprocess_HOOK(), and template_preprocess_field().

    Fail, fail, fail. The code runs, the print statements print, but rendered value of the field changes not one whit.

    <?php
    function dgd7glue_preprocess_field(&$vars) {
      if (
    $vars['element']['#field_name'] == 'field_number') {
       
    $vars['element']['#items'][0]['safe_value'] = 'New value';
       
    $vars['element']['#items'][0]['value'] = 'Newer value';
        print
    '<pre>';
       
    print_r($vars['element']['#items'][0]['safe_value']);
        print
    '</pre>';
        print
    '<pre>';
       
    print_r($vars['element']['#items'][0]['value']);
        print
    '</pre>';
      }
    }
    ?>

    Getting smarter about the debug function (needs devel module enabled), and also finding what finally works:

    <?php
    // only the last one, $vars['items'][0]['#markup'], does anything.
    function dgd7glue_process_field(&$vars) {
      if (
    $vars['element']['#field_name'] == 'field_number') {
       
    krumo($vars);
       
    $vars['classes_array'] = array('so-the-damn-classes-work');
       
    $vars['element']['label_hidden'] = FALSE;
       
    $vars['element']['#items'][0]['safe_value'] .= ' New value';
       
    $vars['element']['#items'][0]['value'] .= ' Newer value';
       
    $vars['element'][0]['#markup'] .= ' Newest value';
       
    $vars['items'][0]['#markup'] .= ' Newester value';
        print
    '<pre>';
       
    print_r($vars['element']['#items'][0]['safe_value']);
        print
    '</pre>';
        print
    '<pre>';
       
    print_r($vars['element']['#items'][0]['value']);
        print
    '</pre>';
        print
    '<pre>';
       
    print_r($vars['element'][0]['#markup']);
        print
    '</pre>';
        print
    '<pre>';
       
    print_r($vars['items'][0]['#markup']);
        print
    '</pre>';
      }
    }
    ?>