Drupal Views – Show One (Most Recent) Item Per Group

Alright, the title is a bit misleading because I’m not using Groups, but it is the best explanation of what I’m achieving with this example. My goal is to show a list of the most recent blog post in each category, where clicking the category takes you to the associated post.

I have a content type called Blog Post which has the following fields:

  • Date (field_blog_date – date field – single value)
  • Category (field_blog_tr_category – taxonomy reference field – single value)
  • Items (field_blog_cr_items – content reference field – unlimited values)

Using Views it’s relatively simple to produce the output shown here:


Here’s what the View configuration looks like:

The category field links to the replacement pattern {{ path }}  from Content: Path [hidden].

This gets us pretty close, but what’s the best way to only show one row per category? The solution I’m using today, which is subject to change (see disclaimer below), is to use hook_views_pre_render() to remove the rows I don’t want to show. The code should explain itself:

 

Here’s the result:

 

Disclaimer: I’m not sure yet if this negatively impacts the way Views serves up this view. I am also not sure how this will behave if there are thousands of records, or if there is a pager involved. For my particular case none of these will be an issue, but they’re things to consider.

UPDATE: If you use a pager to show a specified number of items you are trimming down the original data set, not the result. What this means is that you cannot, for example, ask for “5” items and expect to see 5 categories. What you’d end up with is however many unique categories there are for the first 5 blog posts. So if all 5 were “Drupal” then you’d only get one row in the results.

Tagged with: , , ,
Posted in Development

Leave a Reply

Your email address will not be published. Required fields are marked *

*