Created
May 15, 2017 20:51
-
-
Save djevans/a1a193df28a657f16ac1c0dd12211b5b to your computer and use it in GitHub Desktop.
Views pager plugin with the option to have a different number of items on the first page.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Drupal\views_first_page\Plugin\views\Pager; | |
use Drupal\Core\Form\FormStateInterface; | |
use Drupal\views\Plugin\views\pager\Full; | |
/** | |
* @ViewsPager( | |
* id = "variable_pager", | |
* title = @Translation("Paged output, variable first page"), | |
* short_title = @Translation("Variable first page"), | |
* help = @Translation("Paged output with variable first page, Drupal style"), | |
* theme = "pager", | |
* register_theme = FALSE | |
* ) | |
*/ | |
class VariablePager extends Full { | |
public function getItemsPerPage() { | |
$key = $this->getCurrentPage() <= 1 ? 'items_first_page' : 'items_per_page'; | |
return $this->options[$key] ?? 0; | |
} | |
public function defineOptions() { | |
$options = parent::defineOptions(); | |
$options['items_first_page'] = ['default' => 10]; | |
return $options; | |
} | |
public function buildOptionsForm(&$form, FormStateInterface $form_state) { | |
parent::buildOptionsForm($form, $form_state); | |
$form['items_first_page'] = [ | |
'#title' => t('Items on first page'), | |
'#type' => 'number', | |
'#description' => t('The number of items to show on the first page'), | |
'#default_value' => $this->options['items_first_page'], | |
]; | |
} | |
public function query() { | |
parent::query(); | |
$limit = $this->getCurrentPage() < 1 | |
? $this->options['items_first_page'] | |
: $this->options['items_per_page']; | |
$this->view->query->setLimit($limit); | |
if ($this->getCurrentPage() > 0) { | |
$offset = $this->options['items_first_page'] + (($this->getCurrentPage() - 1) * $this->options['items_per_page']) + $this->options['offset']; | |
$this->view->query->setOffset($offset); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment