2

I'm working in a site that has implemented the template_preprocess_field() hook. I want to change the content of a field but the code works for all the nodes except for the nodes of a content type that have a custom template (node--emploi.tpl.php) It's strange because I have another template for the nodes of the content type named tarif (node--tarif.tpl.php) and in this case the hook is called.

Here the piece of code inside the template node--emploi.tpl.php file:

<div class="editor">
  <?php
  /* At this point the body's h2 do not know what the nid is, so a quick and dirty replace will set it right. */
  print preg_replace('/NO-NID[a-z0-9]*--/', $nid . '--', check_markup($field_stm_emploi_temoignage_body[0]['value'], $field_stm_emploi_temoignage_body[0]['format']));
 ?>
</div>
  • 5
    ...and the field is 100% definitely being rendered as normal in node--emploi.tpl.php? With the same field formatter as is working for other node types? Can you post the code? I suspect you've changed print render($content['field_foo']); to print $content['field_foo'] or some derivative, meaning it's not being rendered through the theme system. Would need to see the template to make sure of course – Clive Jul 19 '16 at 17:28
  • 1
    @Clive Yes you have reason, I test the template with print render($content['field_foo']); and its works fine. Please post your answer to check it as accepted ;-) – Adrian Cid Almaguer Jul 19 '16 at 17:39
  • Sorry, missed your comment somehow. Looks like you took care of it! – Clive Jul 26 '16 at 13:42
  • 1
    @Clive yes I write the answer as guide for other users, but If you want post another answer with more examples or info and I can check it as accepted. You have more experience in this field. – Adrian Cid Almaguer Jul 26 '16 at 13:43
  • Honestly, I think your answer covers it. There are other more advanced solutions (e.g. custom field formatter), but they're probably overly complicated for this – Clive Jul 26 '16 at 14:00
3

As @Clive says the problem was that the code didn't use the render() function for the field output, and in this case the template_preprocess_field() hook is not called.

For the moment I have 2 solutions:

  1. Use the render() function in the template file (node--emploi.tpl.php) to create the output of the field. In this case the template_preprocess_field() hook is called.
  2. Use the template_preprocess_node() hook and check $vars['type'] for my content type. In this case the template file remains equal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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