views_handler_field_counter.inc 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. function option_definition() {
  13. $options = parent::option_definition();
  14. $options['counter_start'] = array('default' => 1);
  15. $options['reverse'] = array('default' => FALSE);
  16. return $options;
  17. }
  18. function options_form(&$form, &$form_state) {
  19. $form['counter_start'] = array(
  20. '#type' => 'textfield',
  21. '#title' => t('Starting value'),
  22. '#default_value' => $this->options['counter_start'],
  23. '#description' => t('Specify the number the counter should start at.'),
  24. '#size' => 2,
  25. );
  26. $form['reverse'] = array(
  27. '#type' => 'checkbox',
  28. '#title' => t('Reverse'),
  29. '#default_value' => $this->options['reverse'],
  30. '#description' => t('Reverse the counter.'),
  31. );
  32. parent::options_form($form, $form_state);
  33. }
  34. function query() {
  35. // do nothing -- to override the parent query.
  36. }
  37. function render($values) {
  38. $reverse = empty($this->options['reverse']) ? 1 : -1;
  39. // Note: 1 is subtracted from the counter start value below because the
  40. // counter value is incremented by 1 at the end of this function.
  41. $counter_start = is_numeric($this->options['counter_start']) ? $this->options['counter_start'] : 0;
  42. $count = ($reverse == -1) ? count($this->view->result) + $counter_start : $counter_start -1;
  43. $pager = $this->view->query->pager;
  44. // Get the base count of the pager.
  45. if ($pager->use_pager()) {
  46. if ($reverse == -1) {
  47. $count = ($pager->total_items + $counter_start - ($pager->get_current_page() * $pager->get_items_per_page()) + $pager->get_offset());
  48. } else {
  49. $count += (($pager->get_items_per_page() * $pager->get_current_page() + $pager->get_offset())) * $reverse;
  50. }
  51. }
  52. // Add the counter for the current site.
  53. $count += ($this->view->row_index + 1) * $reverse;
  54. return $count;
  55. }
  56. }