4

In my current project, whenever a node's image field is empty, I'm filling it with the image from an entity referenced in the node. To pull this off, I'm using this magical piece of code in template.php:

// Implements hook_preprocess_node();
    function mycustomtheme_preprocess_node(&$vars) {

      $node = $vars['node'];
      $field_name = 'field_main_image';
      if (
        isset($node->$field_name) &&
        empty($node->$field_name)
      ) {
        $node_wrapper = entity_metadata_wrapper('node', $node);
        if ($node_wrapper->field_master_reference->raw()) {
          $project = $node_wrapper->field_master_reference->value();
          $vars['content'][$field_name] = field_view_field('node', $project, $field_name);
        }
      }
    }

It works superbly - but with one small problem: it doesn't give the image its correct image style. In fact it just spits out the original image.

How can I force it to use the field's image style?

  • 2
    I'm pretty sure you need to use the API function called image_style_url which can pull in specific image styles. I just don't have time right now to give a fully fleshed out answer. – Danny Englander Apr 24 '13 at 17:12
  • 1
    Thanks for your help, Danny. That's going to be it. I'll investigate and see if I can work out how to incorporate it. – Peter Clemence Apr 24 '13 at 18:30
1

Have you tried render

// Implements hook_preprocess_node();
    function mycustomtheme_preprocess_node(&$vars) {

      $node = $vars['node'];
      $field_name = 'field_main_image';
      if (
        isset($node->$field_name) &&
        empty($node->$field_name)
      ) {
        $node_wrapper = entity_metadata_wrapper('node', $node);
        if ($node_wrapper->field_master_reference->raw()) {
          $project = $node_wrapper->field_master_reference->value();
          $vars['content'][$field_name] = render($vars['content'][$field_name]);
        }
      }
    }
| improve this answer | |
  • Thanks for taking the time to reply, Nikhil. Unfortunately, this breaks the original function - I assume it's because the $project variable is responsible for the image swapping. – Peter Clemence Apr 24 '13 at 18:29

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.