Injecting a block in a Views page on Drupal 7

Submitted by Gold on Wed, 04/06/2011 - 16:34

Views in Drupal 7 is almost there. There's some things that are borked and some that are quite nice.

I have a View with exposed filters and some of these are taxonomy terms. The trouble is I couldn't figure out how to expose these and have them display as a select element. I found Better Exposed Filters which claims to fix this but at the moment it's D7 support is still being worked on. It's actively maintained though so worth keeping an eye on.

So, I was left with this still being an issue.

The fix was a really ugly hack. I coded a block and added it to the sidebar of the view. Functionally it was the same as the one from the exposed filters so all good there. However, we needed it between the text in the header and the view. In the header section of the view you can add as many extra blocks of content as you like. Just click add and insert text or another view. But I wanted a block. Here's what I did to fix that.

  1. Enable PHP filter. It's part of Core
  2. Create a Text Format that uses it and give it access to a role that standard users won't have.
  3. Go to your View, click Add in the header and select a text block.
  4. Set the Text format to php and enter the following;
    try {
    $block = block_load('bf_misc', 'bf_advisors_view_filter');
    $block_content = _block_render_blocks(array($block));
    $build = _block_get_renderable_array($block_content);
    echo drupal_render($build);
    } catch (Exception $e) {
    echo 'Error loading block: ', $e->getMessage(), "\n";

This took several hours of hunting and tweaking to get working. Hopefully this post will save someone the time I went through to get this working.