In hook_node_view() I want to rewrite some fields' values. The $node parameter is not referenced, so how can I rewrite a value?
3 Answers
Take a look at the API documentation for hook_node_view, specifically the comments at the end of the page -> Has anyone been able to successfully modify a node object?. There's talk of using hook_node_load as a solution as well as many of the hooks that are field specific. Note the comments at the bottom of the hook_node_load API page that explains why $nodes is not called by reference but is still changed when changes are made to the variable within the hook re: OOP -> http://php.net/manual/en/language.oop5.references.php.
- In the hook I enter
$node = array()but the node is loaded completely with all fields. Why?hpn– hpn2011-09-19 18:35:23 +00:00Commented Sep 19, 2011 at 18:35 - I also implemented hook_field_load and hook_field_prepare_view but they don't seem to be called.(Tested with
exit()command in hook function body!)hpn– hpn2011-09-19 18:38:45 +00:00Commented Sep 19, 2011 at 18:38
Clear the cache or visit the Modules page to get the hook picked up after you've added it to your module. Then something like this will work.
function my_module_node_view($node, $view_mode, $langcode) { switch($node->type) { case 'foo': $node->content['field_my_field'][0]['#markup'] = 'Changed!'; break; } } - For some reason the changed value is not showing only the original. When I check with dpm the node I can see the value updated, but still the old value is shown to the user. Any tips?giorgio79– giorgio792011-10-05 03:49:53 +00:00Commented Oct 5, 2011 at 3:49
You can do that by implementing template_preprocess_field(&$variables, $hook) in your template.php
function THEMENAME_preprocess_field(&$variables, $hook) { if ($node = menu_get_object()) { if ($node->type == 'car') { if($variables['element']['#field_name'] == 'field_price') { $variables['items']['0']['#markup'] = $new_value; //new value; } } } } Check here: http://tassaf.moriamedia.com/change-field-value-in-node-view/
- Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.2014-02-02 16:58:07 +00:00Commented Feb 2, 2014 at 16:58