Categories
Development

Display a Field Image Outside of the Content Region in Drupal 7 Using Views

I had a project where they wanted a big header image to appear on some of the content pages, above the content. I knew this wouldn’t be too difficult to do, but I was a bit initially stumped as to how best to do it using Drupal 7. I didn’t want to have to install too many modules for it to work, so I decided to start with Views as that module would be installed on the site anyway (of course).

Turns out this is pretty easy to do using Views.

  • First I added an Image field to my Content Type. Then I set the display to Hidden for that field. Easy basic Drupal Content Types stuff so far. Nothing fancy.
  • Then I created a View. A block in this case, and had it display the image field I had created.
  • Under Advanced, I clicked on Contextual Filters. From the list, I chose Content (Nid). I want to filter out by the node id of the current page being viewed. Simple still.
  • Next under the contextual filter options under the When the Filter Value is Not Available  I chose Provide a Default Value and Content ID from the URL from the drop down options.

This simply gets the Content ID from the URL of the current page you are on and then passes it to the filter.

Very easy to setup and works just fine for me!

Categories
Development

Drupal 7 Only Display 1 Image in Teaser

ok, I was working with a content type with an image field that could hold multiple images (0-4 say). Using the Teaser view mode it would display all the images that were associated with that node, which was really cool in the Default view mode, but not so much the Teaser view mode. I only want it to display 1 image there.

So of course, there’s multiple ways to do this, but I found this approach to be the best for me.

I decided to create and edit an template file in this case since there was enough overall customization going on with this node to warrant such changes. So I created a template file name node–myContentType.tpl.php  based on node.tpl.php and stored in in my theme templates directory.

Easy enough. I then threw in there some crazy text just to make sure I was working with the right template file.

Then I just made the following edits to node–myContentType.tpl.php

if ($view_mode == 'teaser') {
  print render($content['myDemoImage'][0]);
} else {
  print render($content['myDemoImage']);
}

The if statement checks what view mode you are in, if it’s teaser which is the one I want to only display 1 image in then it just renders the first photo in myDemoImage field, else display them all.

That’s it, not too bad. Another reason why I do enjoy working with Drupal.