Version 1
[yaffs-website] / web / core / modules / views / src / Plugin / views / field / Counter.php
1 <?php
2
3 namespace Drupal\views\Plugin\views\field;
4
5 use Drupal\Core\Form\FormStateInterface;
6 use Drupal\views\ResultRow;
7
8 /**
9  * Field handler to show a counter of the current row.
10  *
11  * @ingroup views_field_handlers
12  *
13  * @ViewsField("counter")
14  */
15 class Counter extends FieldPluginBase {
16
17   use UncacheableFieldHandlerTrait;
18
19   /**
20    * {@inheritdoc}
21    */
22   public function usesGroupBy() {
23     return FALSE;
24   }
25
26   /**
27    * {@inheritdoc}
28    */
29   protected function defineOptions() {
30     $options = parent::defineOptions();
31     $options['counter_start'] = ['default' => 1];
32     return $options;
33   }
34
35   /**
36    * {@inheritdoc}
37    */
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.'),
44       '#size' => 2,
45     ];
46
47     parent::buildOptionsForm($form, $form_state);
48   }
49
50   /**
51    * {@inheritdoc}
52    */
53   public function query() {
54     // do nothing -- to override the parent query.
55   }
56
57   /**
58    * {@inheritdoc}
59    */
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());
68     }
69     // Add the counter for the current site.
70     $count += $this->view->row_index + 1;
71
72     return $count;
73   }
74
75 }