0

I'm manually printing my node fields on its template (node--TYPE.tpl.php). Something like:

<div class="row">
    <div class="press-year col-md-12">
        <h2><?php print $year; ?></h2>
    </div>  
</div>

And my hook_preprocess_node() looks something like:

function MY_MODULE_preprocess_node(&$vars) {
    switch ($vars['type']) {
        case "my_type":
           if (isset($vars["field_year"]["und"][0])) {
              $vars["year"] = $vars["field_year"]["und"][0]["value"];
          }
        break;
    }
}

The output is fine to all fields; however, when I view the node as administrator, no output is printed. I listed all the variables from the hook to see what was happening with the following code.

function MY_MODULE_preprocess_node(&$vars) {
    var_dump($vars);
    ....
}

I'm getting all fields without the "UND" value, $vars["field_year"][0]["value"] instead of $vars["field_year"]["und"][0]["value"].

Do you have any clue why this happens?

5
  • This is definitely a Drupal 7 site?
    – jamestsymp
    Commented Nov 28, 2013 at 11:40
  • In Drupal 7 hook_preprocess_node is not normally invoked on the node edit form (ie. when you go to 'node/xxx/edit'), there must be a different problem? Commented Nov 28, 2013 at 11:56
  • @jamestsymp yes, D7
    – Teknotica
    Commented Nov 28, 2013 at 12:23
  • @AliceHeaton I've edited my post. I meant seeing the node as admin (E.g.: /node/27)
    – Teknotica
    Commented Nov 28, 2013 at 12:24
  • If you are absolutely certain that it is D7 then I assume there must be another module that is editing the structure of the nodes as I've always had the language passed through. $vars["field_year"][0]["value"] is what you get from Drupal 6.
    – jamestsymp
    Commented Nov 28, 2013 at 15:48

1 Answer 1

1

I was having the same problem with D7. The solution for me was to use field_get_items(...) for reading the node data.

$year_items = field_get_items('node', $variables['node'], 'field_year');
$year = $year_items[0]['value'] + 1;

I found the post on Rendering Drupal 7 fields (the right way) very helpful. It does seem strange that we shouldn't use the $variables provided to the preprocessor and template to read and modify the template variables. I must be missing something.

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.