2

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

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 Sep 19 '11 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 Sep 19 '11 at 18:38
3

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 Oct 5 '11 at 3:49
1

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. – mpdonadio Feb 2 '14 at 16:58

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.