0

I am trying to apply an exposed filter programmatically.

If filter 'a' is set to 'apple' I want to set filter 'b' to 'green'.

Using this code updates the filter. If a user sets the drop-down filter 'a' to 'apple' and clicks apply, then the drop-down filter 'b' is updated to 'green'; but the filter isn't applied. The results still show what the user had set filter 'b' to, instead of updating the results to show if filter 'b' was set to 'green'.

function my_module_views_pre_view(ViewExecutable $view, string $display_id, array $args) {
  if (($view->id() === 'my_view')) {
    $exposedInput = $view->getExposedInput();

    if ($exposedInput['a'] = 'apple') {
      $exposedInput['b'] = 'green';
    } 

    $view->setExposedInput($exposedInput);
  }
}

How can I update the results, not just set the drop-down filter value?

2 Answers 2

1

If you see above code there is syntax mistake use "==" operator:

if ($exposedInput['a'] = 'apple') {

Correct syntax:

  if ($exposedInput['a'] == 'apple') {

if the dependent filter field 'b' is plain text then following code 'll work fine

$exposedInput['b'] = 'green'; 

Note: if dependent filter field 'b' is select list type then need to set key value, not label value otherwise result 'll not render as per logic.

0

In addition to checking the operator in the if statement "==" vs "=", the following should work. Note, the method overrides any existing filters hence the use of array_merge .

$view->setExposedInput(
  array_merge(
    $view->getExposedInput(),
    $may_custom_filters_array
  )
);



$view->pre_execute();
   $view->execute()

Check out:

https://www.drupal.org/forum/support/module-development-and-code-questions/2018-09-17/programmatically-set-exposed-input

https://www.drupal.org/project/drupal/issues/3013530

How can I pass the filter parameters of one view to a different view on the same page?

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