views_handler_field_counter.inc 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /**
  3. * @file
  4. * Definition of views_handler_field_counter.
  5. */
  6. /**
  7. * Field handler to show a counter of the current row.
  8. *
  9. * @ingroup views_field_handlers
  10. */
  11. class views_handler_field_counter extends views_handler_field {
  12. /**
  13. * {@inheritdoc}
  14. */
  15. public function option_definition() {
  16. $options = parent::option_definition();
  17. $options['counter_start'] = array('default' => 1);
  18. $options['reverse'] = array('default' => FALSE);
  19. return $options;
  20. }
  21. /**
  22. * {@inheritdoc}
  23. */
  24. public function options_form(&$form, &$form_state) {
  25. $form['counter_start'] = array(
  26. '#type' => 'textfield',
  27. '#title' => t('Starting value'),
  28. '#default_value' => $this->options['counter_start'],
  29. '#description' => t('Specify the number the counter should start at.'),
  30. '#size' => 2,
  31. );
  32. $form['reverse'] = array(
  33. '#type' => 'checkbox',
  34. '#title' => t('Reverse'),
  35. '#default_value' => $this->options['reverse'],
  36. '#description' => t('Reverse the counter.'),
  37. );
  38. parent::options_form($form, $form_state);
  39. }
  40. /**
  41. * {@inheritdoc}
  42. */
  43. public function query() {
  44. // Do nothing -- to override the parent query.
  45. }
  46. /**
  47. * {@inheritdoc}
  48. */
  49. public function render($values) {
  50. $reverse = empty($this->options['reverse']) ? 1 : -1;
  51. // Note: 1 is subtracted from the counter start value below because the
  52. // counter value is incremented by 1 at the end of this function.
  53. $counter_start = is_numeric($this->options['counter_start']) ? $this->options['counter_start'] : 0;
  54. $count = ($reverse == -1) ? count($this->view->result) + $counter_start : $counter_start - 1;
  55. $pager = $this->view->query->pager;
  56. // Get the base count of the pager.
  57. if ($pager->use_pager()) {
  58. if ($reverse == -1) {
  59. $count = ($pager->total_items + $counter_start - ($pager->get_current_page() * $pager->get_items_per_page()) + $pager->get_offset());
  60. }
  61. else {
  62. $count += (($pager->get_items_per_page() * $pager->get_current_page() + $pager->get_offset())) * $reverse;
  63. }
  64. }
  65. // Add the counter for the current site.
  66. $count += ($this->view->row_index + 1) * $reverse;
  67. return $count;
  68. }
  69. }