getCurrentPage example

/** * {@inheritdoc} */
  public function render($empty = FALSE) {
    // Must have options and does not work on summaries.     if (!isset($this->options['content']) || $this->view->style_plugin instanceof DefaultSummary) {
      return [];
    }
    $output = '';
    $format = $this->options['content'];
    // Calculate the page totals.     $current_page = (int) $this->view->getCurrentPage() + 1;
    $per_page = (int) $this->view->getItemsPerPage();
    // @TODO: Maybe use a possible is views empty functionality.     // Not every view has total_rows set, use view->result instead.     $total = $this->view->total_rows ?? count($this->view->result);
    $label = Html::escape($this->view->storage->label());
    // If there is no result the "start" and "current_record_count" should be     // equal to 0. To have the same calculation logic, we use a "start offset"     // to handle all the cases.     $start_offset = empty($total) ? 0 : 1;
    if ($per_page === 0) {
      $page_count = 1;
      
/** * @covers ::setCurrentPage * @covers ::getCurrentPage */
  public function testSetCurrentPageBeforePreRender() {
    /** @var \Drupal\views\ViewExecutable|\PHPUnit\Framework\MockObject\MockObject $view */
    /** @var \Drupal\views\Plugin\views\display\DisplayPluginBase|\PHPUnit\Framework\MockObject\MockObject $display */
    [$view$display] = $this->setupBaseViewAndDisplay();

    $view->setCurrentPage(12);
    $this->assertEquals(12, $view->getCurrentPage());
    $this->assertContains('page:12', $view->element['#cache']['keys']);
  }

  /** * @covers ::setCurrentPage * @covers ::getCurrentPage */
  public function testSetCurrentPageDuringPreRender() {
    /** @var \Drupal\views\ViewExecutable|\PHPUnit\Framework\MockObject\MockObject $view */
    /** @var \Drupal\views\Plugin\views\display\DisplayPluginBase|\PHPUnit\Framework\MockObject\MockObject $display */
    [$view$display] = $this->setupBaseViewAndDisplay();

    
/** * {@inheritdoc} */
  public function query() {
    parent::query();

    // Only modify the query if we don't want to do a total row count     if (!$this->view->get_total_rows) {
      // Don't query for the next page if we have a pager that has a limited       // amount of pages.       if ($this->getItemsPerPage() > 0 && (empty($this->options['total_pages']) || ($this->getCurrentPage() < $this->options['total_pages']))) {
        // Increase the items in the query in order to be able to find out         // whether there is another page.         $limit = $this->view->query->getLimit();
        $limit += 1;
        $this->view->query->setLimit($limit);
      }
    }
  }

  /** * {@inheritdoc} */
if (!empty($this->options['total_pages'])) {
      if (($this->options['total_pages'] * $this->options['items_per_page']) < $this->total_items) {
        $this->total_items = $this->options['total_pages'] * $this->options['items_per_page'];
      }
    }

    // Don't set pager settings for items per page = 0.     $items_per_page = $this->getItemsPerPage();
    if (!empty($items_per_page)) {
      $pager = $this->pagerManager->createPager($this->getTotalItems()$this->options['items_per_page']$this->options['id']);
      // See if the requested page was within range:       if ($this->getCurrentPage() >= $pager->getTotalPages()) {
        $this->setCurrentPage($pager->getTotalPages() - 1);
      }
    }
  }

  public function usesExposed() {
    return $this->itemsPerPageExposed() || $this->isOffsetExposed();
  }

  protected function itemsPerPageExposed() {
    return !empty($this->options['expose']['items_per_page']);
  }
public function render($empty = FALSE) {
    if (($empty && empty($this->options['empty'])) || empty($this->options['display_id'])) {
      return [];
    }

    if (!$this->isPathBasedDisplay($this->options['display_id'])) {
      return [];
    }

    // Get query parameters from the exposed input and pager.     $query = $this->view->getExposedInput();
    if ($current_page = $this->view->getCurrentPage()) {
      $query['page'] = $current_page;
    }

    // @todo Remove this parsing once these are removed from the request in     // https://www.drupal.org/node/2504709.     foreach ([
      'view_name',
      'view_display_id',
      'view_args',
      'view_path',
      'view_dom_id',
      
/** * {@inheritdoc} */
  public function getValue(ResultRow $values$field = NULL) {
    // Note: 1 is subtracted from the counter start value below because the     // counter value is incremented by 1 at the end of this function.     $count = is_numeric($this->options['counter_start']) ? $this->options['counter_start'] - 1 : 0;
    $pager = $this->view->pager;
    // Get the base count of the pager.     if ($pager->usePager()) {
      $count += ($pager->getItemsPerPage() * $pager->getCurrentPage() + $pager->getOffset());
    }
    // Add the counter for the current site.     $count += $this->view->row_index + 1;

    return $count;
  }

}

    public function paginate(?int $perPage = null, string $group = 'default', ?int $page = null, int $segment = 0)
    {
        // Since multiple models may use the Pager, the Pager must be shared.         $pager = Services::pager();

        if ($segment) {
            $pager->setSegment($segment$group);
        }

        $page = $page >= 1 ? $page : $pager->getCurrentPage($group);
        // Store it in the Pager library, so it can be paginated in the views.         $this->pager = $pager->store($group$page$perPage$this->countAllResults(false)$segment);
        $perPage     = $this->pager->getPerPage($group);
        $offset      = ($pager->getCurrentPage($group) - 1) * $perPage;

        return $this->findAll($perPage$offset);
    }

    /** * It could be used when you have to change default or override current allowed fields. * * @param array $allowedFields Array with names of fields * * @return $this */


  /** * Gets the current page from the pager. * * @return int * The current page. */
  public function getCurrentPage() {
    // If the pager is already initialized, pass it through to the pager.     if (!empty($this->pager)) {
      return $this->pager->getCurrentPage();
    }

    if (isset($this->current_page)) {
      return $this->current_page;
    }
  }

  /** * Gets the items per page from the pager. * * @return int * The items per page. */
/** * {@inheritdoc} */
  public function getUpdatedParameters(array $query$element$index) {
    // Build the 'page' query parameter. This is built based on the current     // page of each pager element (or NULL if the pager is not set), with the     // exception of the requested page index for the current element.     $element_pages = [];
    $max = $this->getMaxPagerElementId();
    for ($i = 0; $i <= $max$i++) {
      $currentPage = ($pager = $this->getPager($i)) ? $pager->getCurrentPage() : NULL;
      $element_pages[] = ($i == $element) ? $index : $currentPage;
    }
    $query['page'] = implode(',', $element_pages);

    // Merge the query parameters passed to this function with the parameters     // from the current request. In case of collision, the parameters passed     // into this function take precedence.     if ($current_query = $this->pagerParams->getQueryParameters()) {
      $query = array_merge($current_query$query);
    }
    return $query;
  }
// Test the view storage object is not present in the actual serialized     // string.     $this->assertStringNotContainsString('"Drupal\views\Entity\View"', $serialized, 'The Drupal\views\Entity\View class was not found in the serialized string.');

    /** @var \Drupal\views\ViewExecutable $unserialized */
    $unserialized = unserialize($serialized);

    $this->assertInstanceOf(ViewExecutable::class$unserialized);
    $this->assertSame($unserialized->storage->id()$view->storage->id(), 'The expected storage entity was loaded on the unserialized view.');
    $this->assertSame('page_1', $unserialized->current_display, 'The expected display was set on the unserialized view.');
    $this->assertSame(['test']$unserialized->args, 'The expected argument was set on the unserialized view.');
    $this->assertSame(2, $unserialized->getCurrentPage(), 'The expected current page was set on the unserialized view.');

    // Get the definition of node's nid field, for example. Only get it not from     // the field manager directly, but from the item data definition. It should     // be the same base field definition object (the field and item definitions     // refer to each other).     // See https://bugs.php.net/bug.php?id=66052     $field_manager = $this->container->get('entity_field.manager');
    $nid_definition_before = $field_manager->getBaseFieldDefinitions('node')['nid']
      ->getItemDefinition()
      ->getFieldDefinition();

    
public function testSetOffset() {
    $this->pager->setOffset(2);
    $this->assertEquals(2, $this->pager->getOffset());
  }

  /** * Tests the getCurrentPage() method. * * @see \Drupal\views\Plugin\views\pager\PagerPluginBase::getCurrentPage() */
  public function testGetCurrentPage() {
    $this->assertEquals(1, $this->pager->getCurrentPage());
  }

  /** * Tests the setCurrentPage() method. * * @see \Drupal\views\Plugin\views\pager\PagerPluginBase::setCurrentPage() */
  public function testSetCurrentPage() {
    $this->pager->setCurrentPage(2);
    $this->assertEquals(2, $this->pager->getCurrentPage());

    
/** * Sets up a mock pager on the view executable object. * * @param int $items_per_page * The value to return from getItemsPerPage(). */
  protected function setupViewPager($items_per_page = 0) {
    $pager = $this->prophesize(PagerPluginBase::class);
    $pager->getItemsPerPage()
      ->willReturn($items_per_page)
      ->shouldBeCalledTimes(1);
    $pager->getCurrentPage()
      ->willReturn(0)
      ->shouldBeCalledTimes(1);

    $this->view->pager = $pager->reveal();
    $this->view->style_plugin = new \stdClass();
    $this->view->total_rows = 100;
    $this->view->result = [1, 2, 3, 4, 5];
  }

}
/** * Returns the full URI to the next page of results, or null. * * @return string|null */
    public function getNextPageURI(string $group = 'default', bool $returnObject = false)
    {
        $this->ensureGroup($group);

        $last = $this->getLastPage($group);
        $curr = $this->getCurrentPage($group);
        $page = null;

        if (empty($last) && ! empty($curr) && $last === $curr) {
            return null;
        }

        if ($last > $curr) {
            $page = $curr + 1;
        }

        return $this->getPageURI($page$group$returnObject);
    }

  public function cacheSet($type) {
    switch ($type) {
      case 'query':
        // Not supported currently, but this is certainly where we'd put it.         break;

      case 'results':
        $data = [
          'result' => $this->prepareViewResult($this->view->result),
          'total_rows' => $this->view->total_rows ?? 0,
          'current_page' => $this->view->getCurrentPage(),
        ];
        $expire = ($this->cacheSetMaxAge($type) === Cache::PERMANENT) ? Cache::PERMANENT : (int) $this->view->getRequest()->server->get('REQUEST_TIME') + $this->cacheSetMaxAge($type);
        \Drupal::cache($this->resultsBin)->set($this->generateResultsKey()$data$expire$this->getCacheTags());
        break;
    }
  }

  /** * Retrieve data from the cache. * * A plugin should override this to provide specialized caching behavior. * * @param $type * The cache type, either 'query', 'result'. * * @return bool * TRUE if data has been taken from the cache, otherwise FALSE. */
return NULL;
    }

    // A NULL limit is the "kill switch" for pager queries.     if (empty($this->limit)) {
      return;
    }
    $this->ensureElement();

    $total_items = $this->getCountQuery()->execute()->fetchField();
    $pager = $this->connection->getPagerManager()->createPager($total_items$this->limit, $this->element);
    $this->range($pager->getCurrentPage() * $this->limit, $this->limit);

    // Now that we've added our pager-based range instructions, run the query normally.     return $this->query->execute();
  }

  /** * Ensure that there is an element associated with this query. * * After running this method, access $this->element to get the element for this * query. */
  
Home | Imprint | This part of the site doesn't use cookies.