VIEWS_QUERY_ALTER doesn't allow unset() but equivalent hook does

Created on 6 June 2023, about 1 year ago
Updated 21 June 2023, about 1 year ago

Problem/Motivation

Implementing hook_views_query_alter allows unsetting a WHERE condition like this:

function mymodule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  unset($query->where[0]);
}

The equivalent code implemented via the VIEWS_QUERY_ALTER event subscriber does not work:

public function viewsQueryAlter(ViewsQueryAlterEvent $event): void {
  $query = $event->getQuery();
  unset($query->where[0]);
}

The code runs and no error is thrown, but the view query is not altered (the results are not affected). This it not a result of a bad implementation on my part. I have step debugged this and I can see that it runs when expected. I can affect the view results by using methods of the QueryPluginBase class (for example $query->addWhere()), but I cannot directly unset a WHERE condition the same way that I can when using the equivalent Drupal core hook.

Regardless of whether you think unsetting a WHERE condition this way is correct (there is no method to do it, so who can say?), I think the event should behave exactly the same way as the core hook, or else there are bound to be issues when converting hooks to events. Until this is fixed, I'm unfortunately stuck using the hook.

I suspect that this has something to do with not passing $query by reference, but I've looked into replicating the way $form is passed from the form alter event, and haven't had any luck.

Steps to reproduce

Proposed resolution

Remaining tasks

User interface changes

API changes

Data model changes

🐛 Bug report
Status

Active

Version

4.0

Component

Code

Created by

🇺🇸United States maskedjellybean Portland, OR

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @maskedjellybean
  • 🇮🇩Indonesia el7cosmos 🇮🇩 GMT+7

    This works fine on my end, I can see the where group removed both in step debugging and in the results.

    Can you try to update the test and validate it in \Drupal\Tests\views_event_dispatcher\Kernel\ViewBuildEventTest::onQueryAlter?

  • 🇺🇸United States maskedjellybean Portland, OR

    Ran into this again on an unrelated piece of code and once again reverting back to hook_views_query_alter fixes it. I definitely think this is a real issue.

    I don't have my local environment setup for phpunit yet but I'll try to validate this.

Production build 0.69.0 2024