3 namespace Drupal\views\Plugin\views\field;
5 use Drupal\Core\Form\FormStateInterface;
6 use Drupal\views\ResultRow;
9 * Field handler to show a counter of the current row.
11 * @ingroup views_field_handlers
13 * @ViewsField("counter")
15 class Counter extends FieldPluginBase {
17 use UncacheableFieldHandlerTrait;
22 public function usesGroupBy() {
29 protected function defineOptions() {
30 $options = parent::defineOptions();
31 $options['counter_start'] = ['default' => 1];
38 public function buildOptionsForm(&$form, FormStateInterface $form_state) {
39 $form['counter_start'] = [
40 '#type' => 'textfield',
41 '#title' => $this->t('Starting value'),
42 '#default_value' => $this->options['counter_start'],
43 '#description' => $this->t('Specify the number the counter should start at.'),
47 parent::buildOptionsForm($form, $form_state);
53 public function query() {
54 // do nothing -- to override the parent query.
60 public function getValue(ResultRow $values, $field = NULL) {
61 // Note: 1 is subtracted from the counter start value below because the
62 // counter value is incremented by 1 at the end of this function.
63 $count = is_numeric($this->options['counter_start']) ? $this->options['counter_start'] - 1 : 0;
64 $pager = $this->view->pager;
65 // Get the base count of the pager.
66 if ($pager->usePager()) {
67 $count += ($pager->getItemsPerPage() * $pager->getCurrentPage() + $pager->getOffset());
69 // Add the counter for the current site.
70 $count += $this->view->row_index + 1;