After modifying the views queries in hook_views_query_alter() the pager is broken

Created on 12 November 2016, over 8 years ago
Updated 15 May 2023, about 2 years ago

Hi,

if I add a addWhere() to the query object in hook_views_query_alter(), my items get filtered like desired in the views pager pages. But the number of the items is broken then. There not shown 10 items anymore. But 10 items minus the number of filtered items. I have used the following code to filter the items:

/**
 * Implements hook_views_query_alter().
 */
function permissions_by_term_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  $query = $view->getQuery();
  $accessCheck = \Drupal::service('permissions_by_term.access_check');

  if (!$accessCheck->canUserBypassAllAccessChecks()) {
    $allowed_nids = $accessCheck->getAllowedNidsByCurrentUsersUid();
    if (!empty($allowed_nids) && in_array('node_field_data', array_keys($query->relationships))) {
      $view->query->addWhere('pbt', 'node_field_data.nid', $allowed_nids, 'IN');
    }
  }

  return $view;
}

What am I doing wrong? How can I ensure to have always the pre-defined number of items on each pager page?

πŸ› Bug report
Status

Postponed: needs info

Version

10.1 ✨

Component
ViewsΒ  β†’

Last updated about 8 hours ago

Created by

πŸ‡©πŸ‡ͺGermany Peter Majmesku πŸ‡©πŸ‡ͺDΓΌsseldorf

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

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • πŸ‡³πŸ‡±Netherlands Lendude Amsterdam

    It sounds like #12 might be the thing, that distinct causes this. There are older indications that distinct can cause some problem when looking at the comment in \Drupal\views\Plugin\views\query\Sql::execute

    // Count queries must be run through the preExecute() method.
          // If not, then hook_query_node_access_alter() may munge the count by
          // adding a distinct against an empty query string
          // (e.g. COUNT DISTINCT(1) ...) and no pager will return.
          // See \Drupal\Core\Database\Query\PagerSelectExtender::execute()
          // See https://www.drupal.org/node/1046170.
    

    So we might be doing something special for distinct in count queries?

    Some confirmation that this is indeed the issue would be great, sotra feels like stabbing in the dark right now.

  • πŸ‡³πŸ‡±Netherlands johnv

    Having the same problem when filtering in hook_views_post_execute() or hook_views_pre_render() .

  • Status changed to Closed: outdated 1 day ago
  • πŸ‡ΊπŸ‡ΈUnited States smustgrave

    Since there's been no follow up to #17 going to close this one out.

Production build 0.71.5 2024