DRUPAL TOOLBOX

LET’S FIX STUFF AND BUILD THINGS. MISTAKES ARE OK.

A simple replacement for group-by / grouping row limit views

I examined a group-by view displaying one recent item for each of a handful of taxonomy terms, which must also exclude some featured nodes on the same page.  Using either the standard group-by view setting or the more featureful Views Grouping Row Limit module, I found that this single view consumed ~120MB of memory.


The following method is a little roundabout, but is quick to implement and far less resource-intensive.


    Create a views block with desired item display.

    Set contextual arguments for the grouping factor (e.g. a taxonomy term) and for NID (set to "Exclude").

    Load and alter your view in a block with code like the following, added for example to a block in a custom module.


The below code loads the block view as a base, adjusts arguments, and prints the results for each "group", run as a separate query.

Even reloading the view once per primary contextual argument (e.g. term), this in my case wholly removed the extra memory burden of the ordinary "Group By" or "Grouping Row Limit" view.

/**

 * Replacement for group-by in "latest posts by term" view.

 *

 * Prepare a few variables first: the NIDs we will want to exclude (empty to start with in this example),

 * and the array of primary contextual arguments to run through (these were originally the grouping field).

 */

$exclude_nids = array();

// Sample primary contextual argument configuration: load each term TID in a specific order

$tids = array(1,2,3,4,5,6);


/*

 * Loop through each iteration of this argument, building a view with one result.

 * Store each nid for exclusion on the next round, and render the result for this iteration.

 */

foreach ($tids as $tid) {

  // Build string NID argument

  $nid_args = implode(',', $exclude_nids);


  // Load the view via views_get_view()

  $view = views_get_view('viewname'); // viewname: e.g. 'posts'

  $view->set_display('display'); // display: e.g. 'block_2'


  // Set arguments for term and excluded nids.

  // Set items_per_page to 1 for this view.

  $view->set_arguments(array($tid, $nid_args));

  $view->items_per_page = 1;


  // Execute view

  $view->pre_execute();

  $view->execute();


  // Get resulting nid and add to exclusions list.

  $result = $view->result;

  $exclude_nids[] = $result[0]->nid;


  // Display rendered view result

  print $view->render('display');

}