Example: View Block to render part of Node's page view
Our site displays information about artists. I wanted to add a short photo and biography for each artist, but couldn't find a way to get it to fit in the main content area (between the left sidebar menu and the right sidebar blocks), while maintaining a nice layout for the page. I decided to display the photo-biography at the top of the right sidebar in a block. This actually highlights the biography nicely and helps "use up" some otherwise unused real estate on the sidebar. Sweet - but how did I display part of the contents of a node in a block by that node's page? Easy - Contextual View Block to the rescue...
Here's my recipe:
- Create a CCK type with fields for the various bits of data you have to display. Mine had "photo" and "bio" fields, in addition to others.
- Use the CCK Display Fields to hide all the fields you want displayed in the Block (for full view in any case - you may want to show them in teaser view).
- Create a Block view with no title (at least I didn't want a title), set to display 1 node. (I use a List view type with some CSS to get rid of the bullet to display content in blocks that should not really be lists).
- Select the Fields you want to show in your block (the same ones you "hid" in step 2)
- Filter based on Node Type
- Add the Contextual View Block magic, to tell the view to pull in the data from the very node being displayed... Add a "Node:ID" argument, with "Use Empty Text" as a default. Add the following Argument Code:
if (arg(0) == 'node' && is_numeric(arg(1))) {
$args[0] = arg(1);
}
return $args;
**see note below
- Go to admin/blocks and configure the block to show up on the right sidebar with a very light weight (so it's at the top). Set the block to only display on pages that will display your CCK node type.
Voila!
This is such a great technique! I've used it to create a little context-sensitive help block (http://drupal.org/node/224531), and to create a context-sensitive "news" block that only shows news stories related to the current page. A similar technique is used to embed a context-sensitive view that pulls in a small gallery of images related to the current page (http://drupal.org/node/221919). What a little beauty!
**Note: In our case, not all artists have biographies, so we only want the "bio-block" to show up when there is biography data in the node. We achieve this by using the argument code:
if (arg(0) == 'node' && is_numeric(arg(1))) {
$node = node_load(arg(1));
if ($node->field_YOUR_FIELD) {
$args[0] = arg(1);
}
}
return $args; where field_YOUR_FIELD is the name of one of the fields you are trying to display. If there is not data in that field, then the block will be empty, and thus not show up!
