3

Drupal 7.

Is it possible to pass an argument to the contextual filter to limit number of items to display in a View from the UI?

IOW: can you pass an argument that replicates the Number Of Items portion of the Pager?

I have a node form which uses View Fields to display a view of related items. I want to pass an argument via the Field Display which limits the # of records.

If this must be done programmatically, how do I hook into the view 'contextually'... ie. so that the hook overrides the Number Of Items when the visitor is on a particular page (a Node of a certain Content Type.)

  • Do you mean programmatically or by way of the URL? – Clive Sep 17 '14 at 18:58
  • I mean via the URL. I edited the question, which I -thought- was straightforward. <sigh> I'm getting tired of re-creating the same view over and over depending on where it's called from. TIA. – jchwebdev Sep 17 '14 at 19:11
1

I don't think it's possible through the Views interface. But I think you could probably do it through a small custom module.

function MYMODULE_views_pre_build(&$view) {
  if ($view->name == 'view_name') {
    $limit = $arg(1) //where $arg is the argument from your url
    $view->items_per_page = $limit;
  }
}
  • Thanks. Then I guess I need one more 'if'. How do I filter this so that it only applies the limit if the page being displayed is a) a node and b) is of a certain content type? – jchwebdev Sep 17 '14 at 20:51
  • It depends on how you have your view set up. If you happen to be using a contextual filter for content type, that will be available in the view var you get passed in the pre_build. So if you happen to have ether the NID or Content Type as contextual filters, that would be in $view['args'][(position it's in in the view)]. – Jance Sep 18 '14 at 13:39
0

In depth you can do something like this:

/**
 * Implementation of hook_views_pre_build().
 */
function modulename_views_pre_build(&$view) {
  // Offset: starting point (position) of the subset of nodes
  if (!empty($_REQUEST['offset'])) {
    $offset = (int) $_REQUEST['offset'];
    if ($offset >= 0) {
      $view->set_offset($offset);
    }
  }
  // Limit: is the number of nodes to return
  if (!empty($_REQUEST['limit'])) {
    $limit = (int) $_REQUEST['limit'];
    if ($limit >= 0) {
      $view->set_items_per_page($limit);
    }
  }
}

Now when you'll execute your view the URL should be something like this:

http://an-awesome-drupal-site/your-view-path?limit=25&offset=5 and its done ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.