Counter field with leading zero option

Created on 16 June 2012, about 12 years ago
Updated 2 March 2023, over 1 year ago

To add a leading zero to the counter field I created a new handler.

I post it here so you could maybe add this to the generic Views code.

The below is the original counter code with my own customizations.

class customization_handler_field_counter extends views_handler_field {
  function option_definition() {
    $options = parent::option_definition();
    $options['counter_start'] = array('default' => 1);
    $options['leading_zero'] = array('default' => false);
    return $options;
  }

  function options_form(&$form, &$form_state) {
    $form['counter_start'] = array(
      '#type' => 'textfield',
      '#title' => t('Starting value'),
      '#default_value' => $this->options['counter_start'],
      '#description' => t('Specify the number the counter should start at.'),
      '#size' => 2,
    );
    $form['leading_zero'] = array(
      '#type' => 'checkbox',
      '#title' => t('Leading Zero'),
      '#default_value' => $this->options['leading_zero'],
      '#description' => t('Should the counter contain a leading zero if below 10.'),
    );

    parent::options_form($form, $form_state);
  }

  function query() {
    // do nothing -- to override the parent query.
  }

  function render($values) {
    // Note:  1 is subtracted from the counter start value below because the
    // counter value is incremented by 1 at the end of this function.
    $count = is_numeric($this->options['counter_start']) ? $this->options['counter_start'] - 1 : 0;
    $pager = $this->view->query->pager;
    // Get the base count of the pager.
    if ($pager->use_pager()) {
      $count += ($pager->get_items_per_page() * $pager->get_current_page() + $pager->get_offset());
    }
    // Add the counter for the current site.
    $count += $this->view->row_index + 1;
    
    if ($this->options['leading_zero'] && $count < 10) {
      $count = '0' . $count;
    }

    return $count;
  }
}
Feature request
Status

Needs work

Version

3.3

Component

Code

Created by

🇮🇱Israel Eyal Shalev

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.69.0 2024