2

I have a view object and I'd like to get the contextual filters that were passed to it.

I have this tidbit of code that prints out the arguments field name.

if (!empty($view->argument)) {
  foreach ($view->argument as $id => $arg) {
    print $arg->field;
  }
}

I'm trying to get the values of those fields.

9

$view->args[0] returns the first argument.

5

A dynamic solution:

foreach ($view->argument as $id => $arg) {
  $pos = $arg->position;
  print $view->args[$pos];
}
1

For Drupal 8 I've used such variant based on the answers above.

foreach ($view->argument as $arg) {
    if ($arg->getPluginId() != 'node_nid') {
      continue;
    }
    $node = Node::load($arg->getValue());
    break;
}
0

Maybe you could use:

$info = $view->get_items($type);

Where $type is some type from here: https://api.drupal.org/api/views/includes%21view.inc/function/views_object_types/7

Probably for your case could be:

$contextual_filters = $view->get_items('argument');

Ahother option could be to target a specific contextual filter for performing some alterations (i.e. hook_views_whatever): In that case you could probably use:

$my_filter = $view->get_item($display_id, $type, $id);

Perform whatever you want to do with that filter, and then:

$view->set_item($display_id, $type, $id, $my_filter);
  • Kindly test your solution before posting here. "Maybe", "probably" isnt something the people want to see here. :) – Pratip Ghosh Feb 3 '16 at 10:04
  • Hi Pratip Ghosh, "Maybe" refers to one choice you could use and "probably" means here that is the best solution that I can think whitout knowing where that code is being called. That $view object could come from many hooks, handlers... – TuWebO Feb 29 '16 at 16:04

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.