2

I need to set a contextual filter programmatically and almost every view I have will have this filter. However, some wont and will have other contextual filters instead.

I have tried following the examples in here but this will just set the first argument to be my filter value regardless of what field is it for.

In views_pre_build I get the keyed arguments list under $view->argument and can do ->setArgument() but this doesn't change the set of results.

Is there an easier way of setting a specific contextual filter?

3 Answers 3

0

Contextual filters use query string params. You could hard code these into the URL. If using a Url object, you can pass a third argument ['query' => ['param1 => 'param1_value',...]]. Try setting a filter and seeing what the URL param name & value is after doing so.

In hook_views_pre_build(), you can also set the filter value directly:

$view->filter['filter_name']->value = 'filter_value';

It's helpful to have Xdebug so you can see the names of existing filters. If you don't have xdebug, try finding the correct filter name in the ->filter property, then find the desired filter value, and put 2 and 2 together.

3

If you have the $view object, you can pass contextual filter params using the setArguments() method. Here is an example I'm using to pass four nids to the view to filter the results contextually:

$view->setArguments(['125+109+110+111']);
0
function your_module_views_pre_build(ViewExecutable $view) {
  if ($view->id() == 'viewname' && $view->getDisplay()->display['id'] == 'machinenameOfDisplay') {
      dump( $view->args ); //you will get all the argument
      $view->args[1] = 'your value' //set specific argument
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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