Am currently trying to implement a node referenced image field on my Drupal 7 site that will change it's 'view mode' depending on programmatical logic just before render. The field is currently being rendered on a number of content types via their display mode settings, each of which are using the field formatter 'Rendered node'.
first attempt
My first idea was to implement the following, considering a hook is a hook is a hook:
function HOOK_field_formatter_view( $entity_type, $entity, $field ... ){
switch ($display['type']) {
case 'node_reference_node':
/* Programatical logic here to modfy field render settings */
break;
}
}
Obviously exchanging HOOK for my module's name.
It didn't really matter if the above would fire before or after the original function node_reference_field_formatter_view
in node_reference.module
because I would either override it's output entirely or, hopefully, modify its values before rendering. The only problem is, the above hook seems to function only on a per module basis — i.e. it's not site-wide, so basically it doesn't fire for my module.
Now obviously I can write my own field formatter to output a rendered node. But it seems a bit of a waste considering there is already one that exists.
other approaches
My other approaches have been to HOOK_preprocess_node
and HOOK_preprocess_field
but the former doesn't contain any view_mode
information, and the latter contains at least 5 different complicated structures that all have references to a view_mode
property at different levels — and it feels rather hacky to have to modify each of their values. Even when I've changed certain view_mode
properties the resulting image doesn't change.
question
Does anyone know of a clean way to step in before a field formatter renders (of a contrib module) and change it's settings on a per page request basis — i.e. by not having to change the actual content type's permanent view mode settings?
hook_field_formatter_view_alter()
or similar for probably over a year now, it just doesn't exist unfortunately. FYIhook_preprocess_node()
definitely does haveview_mode
available to it, it's in$vars['view_mode']
, not$vars['node']->view_mode
which you might have been tempted to try.view_mode
onhook_preprocess_node
, foolish me! I wonder if anything likehook_field_formatter_view_alter()
this exists in D8...