0

I need to use a node API hook to alter some node content before it's displayed, in Drupal 7.

It just occurred to me though that if I used hook_node_view() it will not effect the output of a View that display's those nodes fields (right?).

I need to alter the fields in both the display of the node and the node's display in any views. Hopefull this can be done in one function, and not have duplicate code in both hook_node_view() and hook_views_pre_render() or function hook_views_data()whichever hook is used.

2

There are multiple ways in which this could be achieved:

  1. Override the field itself in your theme with template_preprocess_field().
  2. If the customization is more towards the markup, you can directly achieve that by overriding the field template.
  3. Or you could just write a field formatter for this field, and select it in the field settings of the views and the view-mode (manage display) of your content type.
  • Thanks! I didn't consider #1 because I don't have any experience doing that. I already have several custom module hooks so I thought I would just make another. I'll look into template_preprocess_field though, that might be just what I need. #2 won't work for me because, what I'm doing is I'm not displaying a field at all if certain conditionals are met. I did consider #3 and that would be very clean but maybe a little more effort. And if a field formatter is already selected for the field then can I have two field formatters for one field?? – Dan Mantyla Oct 12 '18 at 15:50
  • BTW, I need to alter the field for only certain node types and sometimes only when certain tags are chosen for that node type. Is it still possible to use template_preprocess_field for this? – Dan Mantyla Oct 12 '18 at 16:15
  • 2
    @DanMantyla Yep! In the preprocess field you should be able to find the node with something like $variables['element']['#object'] and then use any of its properties (type, status, published, etc) or even field values. – AjitS Oct 12 '18 at 16:26

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.