You are here

formatted_number.module in Formatted Number 7

Same filename and directory in other branches
  1. 6 formatted_number.module

Defines numeric field types where the thousand and decimal separators are inherited from the Format Number API module.

File

formatted_number.module
View source
<?php

/**
 * @file
 * Defines numeric field types where the thousand and decimal separators
 * are inherited from the Format Number API module.
 */

/**
 * Implements hook_help().
 */
function formatted_number_help($path, $arg) {
  switch ($path) {
    case 'admin/help#formatted_number':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The Formatted Number module defines various numeric field types for the Field module. Numbers can be in integer, decimal, or floating-point form, and they will inherit the format from the Format Number API module when displayed. Number fields can be limited to a specific set of input values or to a range of values. See the <a href="@field-help">Field module help page</a> for more information about fields.', array(
        '@field-help' => url('admin/help/field'),
      )) . '</p>';
      return $output;
  }
}

/**
 * Implements hook_field_info().
 */
function formatted_number_field_info() {
  return array(
    'formatted_tinyint' => array(
      'label' => t('Formatted tiny integer'),
      'description' => t('Store a number in the database as a tiny integer (-128 to 127).'),
      'settings' => array(
        'min' => -128,
        'max' => 127,
        'max_length' => 4,
      ),
      'instance_settings' => array(
        'min' => '',
        'max' => '',
        'prefix' => '',
        'suffix' => '',
      ),
      'default_widget' => 'formatted_number',
      'default_formatter' => 'formatted_number_integer',
    ),
    'formatted_tinyint_unsigned' => array(
      'label' => t('Formatted tiny integer (unsigned)'),
      'description' => t('Store a number in the database as a tiny unsigned integer (0 to 255).'),
      'settings' => array(
        'min' => 0,
        'max' => 255,
        'max_length' => 4,
      ),
      'instance_settings' => array(
        'min' => '',
        'max' => '',
        'prefix' => '',
        'suffix' => '',
      ),
      'default_widget' => 'formatted_number',
      'default_formatter' => 'formatted_number_integer',
    ),
    'formatted_smallint' => array(
      'label' => t('Formatted small integer'),
      'description' => t('Store a number in the database as a small integer (-32768 to 32767).'),
      'settings' => array(
        'min' => -32768,
        'max' => 32767,
        'max_length' => 7,
      ),
      'instance_settings' => array(
        'min' => '',
        'max' => '',
        'prefix' => '',
        'suffix' => '',
      ),
      'default_widget' => 'formatted_number',
      'default_formatter' => 'formatted_number_integer',
    ),
    'formatted_smallint_unsigned' => array(
      'label' => t('Formatted small integer (unsigned)'),
      'description' => t('Store a number in the database as a small unsigned integer (0 to 65535).'),
      'settings' => array(
        'min' => 0,
        'max' => 65535,
        'max_length' => 7,
      ),
      'instance_settings' => array(
        'min' => '',
        'max' => '',
        'prefix' => '',
        'suffix' => '',
      ),
      'default_widget' => 'formatted_number',
      'default_formatter' => 'formatted_number_integer',
    ),
    'formatted_mediumint' => array(
      'label' => t('Formatted medium integer'),
      'description' => t('Store a number in the database as a medium integer (-8388608 to 8388607)'),
      'settings' => array(
        'min' => -8388608,
        'max' => 8388607,
        'max_length' => 10,
      ),
      'instance_settings' => array(
        'min' => '',
        'max' => '',
        'prefix' => '',
        'suffix' => '',
      ),
      'default_widget' => 'formatted_number',
      'default_formatter' => 'formatted_number_integer',
    ),
    'formatted_mediumint_unsigned' => array(
      'label' => t('Formatted medium integer (unsigned)'),
      'description' => t('Store a number in the database as a medium unsigned integer (0 to 16777215).'),
      'settings' => array(
        'min' => 0,
        'max' => 16777215,
        'max_length' => 10,
      ),
      'instance_settings' => array(
        'min' => '',
        'max' => '',
        'prefix' => '',
        'suffix' => '',
      ),
      'default_widget' => 'formatted_number',
      'default_formatter' => 'formatted_number_integer',
    ),
    'formatted_integer' => array(
      'label' => t('Formatted integer'),
      'description' => t('Store a number in the database as an integer (-2147483648 to 2147483647).'),
      'settings' => array(
        'min' => -2147483648,
        'max' => 2147483647,
        'max_length' => 15,
      ),
      'instance_settings' => array(
        'min' => '',
        'max' => '',
        'prefix' => '',
        'suffix' => '',
      ),
      'default_widget' => 'formatted_number',
      'default_formatter' => 'formatted_number_integer',
    ),
    'formatted_integer_unsigned' => array(
      'label' => t('Formatted integer (unsigned)'),
      'description' => t('Store a number in the database as an unsigned integer (0 to 4294967295).'),
      'settings' => array(
        'min' => 0,
        'max' => 4294967295,
        'max_length' => 15,
      ),
      'instance_settings' => array(
        'min' => '',
        'max' => '',
        'prefix' => '',
        'suffix' => '',
      ),
      'default_widget' => 'formatted_number',
      'default_formatter' => 'formatted_number_integer',
    ),
    'formatted_decimal' => array(
      'label' => t('Formatted decimal'),
      'description' => t('Store a number in the database in a fixed decimal format.'),
      'settings' => array(
        'min' => '',
        'max' => '',
        'max_length' => 30,
        'precision' => 10,
        'scale' => 2,
      ),
      'instance_settings' => array(
        'min' => '',
        'max' => '',
        'prefix' => '',
        'suffix' => '',
      ),
      'default_widget' => 'formatted_number',
      'default_formatter' => 'formatted_number_decimal',
    ),
    'formatted_float' => array(
      'label' => t('Formatted float'),
      'description' => t('Store a number in the database in a floating point format.'),
      'settings' => array(
        'min' => '',
        'max' => '',
        'max_length' => 30,
      ),
      'instance_settings' => array(
        'min' => '',
        'max' => '',
        'prefix' => '',
        'suffix' => '',
      ),
      'default_widget' => 'formatted_number',
      'default_formatter' => 'formatted_number_decimal',
    ),
  );
}

/**
 * Implements hook_field_settings_form().
 */
function formatted_number_field_settings_form($field, $instance, $has_data) {
  $settings = $field['settings'];
  $form = array();
  if ($field['type'] == 'formatted_decimal') {
    $form['precision'] = array(
      '#type' => 'select',
      '#title' => t('Precision'),
      '#options' => drupal_map_assoc(range(10, 32)),
      '#default_value' => $settings['precision'],
      '#description' => t('The total number of digits to store in the database, including those to the right of the decimal.'),
      '#disabled' => $has_data,
    );
    $form['scale'] = array(
      '#type' => 'select',
      '#title' => t('Scale'),
      '#options' => drupal_map_assoc(range(0, 10)),
      '#default_value' => $settings['scale'],
      '#description' => t('The number of digits to the right of the decimal.'),
      '#disabled' => $has_data,
    );
  }
  return $form;
}
function formatted_number_field_info_alter(&$info) {

  // Add min/max settings to decimal field types.
  if (isset($info['formatted_decimal'])) {
    $precision = $info['formatted_decimal']['settings']['precision'];
    $scale = $info['formatted_decimal']['settings']['scale'];
    $min = (double) ('-' . str_repeat('9', $precision - $scale) . '.' . str_repeat('9', $scale));
    $max = (double) (str_repeat('9', $precision - $scale) . '.' . str_repeat('9', $scale));
    $info['formatted_decimal']['settings']['min'] = $min;
    $info['formatted_decimal']['settings']['max'] = $max;
  }
}

/**
 * Implements hook_field_instance_settings_form().
 */
function formatted_number_field_instance_settings_form($field, $instance) {
  $settings = $instance['settings'];
  $form['min'] = array(
    '#type' => 'textfield',
    '#title' => t('Minimum'),
    '#default_value' => $settings['min'],
    '#description' => t('The minimum value that should be allowed in this field. Leave blank for no minimum.'),
    '#element_validate' => array(
      '_element_validate_limit',
    ),
  );
  $form['max'] = array(
    '#type' => 'textfield',
    '#title' => t('Maximum'),
    '#default_value' => $settings['max'],
    '#description' => t('The maximum value that should be allowed in this field. Leave blank for no maximum.'),
    '#element_validate' => array(
      '_element_validate_limit',
    ),
  );
  $form['prefix'] = array(
    '#type' => 'textfield',
    '#title' => t('Prefix'),
    '#default_value' => $settings['prefix'],
    '#size' => 60,
    '#description' => t("Define a string that should be prefixed to the value, like '\$ ' or '&euro; '. Leave blank for none. Separate singular and plural values with a pipe ('pound|pounds')."),
  );
  $form['suffix'] = array(
    '#type' => 'textfield',
    '#title' => t('Suffix'),
    '#default_value' => $settings['suffix'],
    '#size' => 60,
    '#description' => t("Define a string that should be suffixed to the value, like ' m', ' kb/s'. Leave blank for none. Separate singular and plural values with a pipe ('pound|pounds')."),
  );
  return $form;
}

/**
 * Validate the element for min/max limits.
 */
function _element_validate_limit($element, &$form_state) {
  $value = $element['#value'];
  $field_name = $form_state['values']['instance']['field_name'];
  $field = $form_state['field'][$field_name][LANGUAGE_NONE]['field'];
  if ($value != '' && !is_numeric($value)) {
    form_error($element, t('%name must be a number.', array(
      '%name' => $element['#title'],
    )));
  }
  if ($value != '' && isset($field['settings']['min'])) {
    if ($element['#name'] == 'instance[settings][min]' && $value < $field['settings']['min']) {
      form_error($element, t('%name: the value may be no less than %min.', array(
        '%name' => $element['#title'],
        '%min' => $field['settings']['min'],
      )));
    }
    if ($element['#name'] == 'instance[settings][max]' && $value > $field['settings']['max']) {
      form_error($element, t('%name: the value may be no greater than %max.', array(
        '%name' => $element['#title'],
        '%max' => $field['settings']['max'],
      )));
    }
  }
}

/**
 * Implements hook_field_validate().
 *
 * Possible error codes:
 * - 'formatted_number_min': The value is less than the allowed minimum value.
 * - 'formatted_number_max': The value is greater than the allowed maximum value.
 */
function formatted_number_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  foreach ($items as $delta => $item) {
    if ($item['value'] != '') {
      $min = is_numeric($instance['settings']['min']) ? $instance['settings']['min'] : $field['settings']['min'];
      if (is_numeric($min) && $item['value'] < $min) {
        $errors[$field['field_name']][$langcode][$delta][] = array(
          'error' => 'formatted_number_min',
          'message' => t('%name: the value may be no less than %min.', array(
            '%name' => $instance['label'],
            '%min' => $min,
          )),
        );
      }
      $max = is_numeric($instance['settings']['max']) ? $instance['settings']['max'] : $field['settings']['max'];
      if (is_numeric($max) && $item['value'] > $max) {
        $errors[$field['field_name']][$langcode][$delta][] = array(
          'error' => 'formatted_number_max',
          'message' => t('%name: the value may be no greater than %max.', array(
            '%name' => $instance['label'],
            '%max' => $max,
          )),
        );
      }
    }
  }
}

/**
 * Implements hook_field_presave().
 */
function formatted_number_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  if ($field['type'] == 'formatted_decimal') {

    // Let PHP round the value to ensure consistent behavior across storage
    // backends.
    foreach ($items as $delta => $item) {
      if (isset($item['value'])) {
        $items[$delta]['value'] = round($item['value'], $field['settings']['scale']);
      }
    }
  }
}

/**
 * Implements hook_field_is_empty().
 */
function formatted_number_field_is_empty($item, $field) {
  return !is_numeric($item['value']);
}

/**
 * Implements hook_field_formatter_info().
 */
function formatted_number_field_formatter_info() {
  return array(
    'formatted_number_integer' => array(
      'label' => t('Default'),
      'field types' => array_diff(array_keys(formatted_number_field_info()), array(
        'formatted_decimal',
        'formatted_float',
      )),
      'settings' => array(
        'scale' => 0,
        'prefix_suffix' => TRUE,
      ),
    ),
    'formatted_number_decimal' => array(
      'label' => t('Default'),
      'field types' => array(
        'formatted_decimal',
        'formatted_float',
      ),
      'settings' => array(
        'scale' => 2,
        'prefix_suffix' => TRUE,
      ),
    ),
    'formatted_number_unformatted' => array(
      'label' => t('Unformatted'),
      'field types' => array_keys(formatted_number_field_info()),
    ),
  );
}

/**
 * Implements hook_field_formatter_settings_form().
 */
function formatted_number_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  if ($display['type'] == 'formatted_number_decimal' || $display['type'] == 'formatted_number_integer') {
    if ($display['type'] == 'formatted_number_decimal') {
      $element['scale'] = array(
        '#type' => 'select',
        '#title' => t('Scale'),
        '#options' => drupal_map_assoc(range(0, isset($field['settings']['scale']) ? $field['settings']['scale'] : 20)),
        '#default_value' => $settings['scale'],
        '#description' => t('The number of digits to the right of the decimal.'),
      );
    }
    $element['prefix_suffix'] = array(
      '#type' => 'checkbox',
      '#title' => t('Display prefix and suffix.'),
      '#default_value' => $settings['prefix_suffix'],
    );
  }
  return $element;
}

/**
 * Implements hook_field_formatter_settings_summary().
 */
function formatted_number_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $summary = array();
  if ($display['type'] == 'formatted_number_decimal' || $display['type'] == 'formatted_number_integer') {
    $summary[] = format_number(is_numeric($field['settings']['max']) ? $field['settings']['max'] : 1234.123456789, $settings['scale']);
    if ($settings['prefix_suffix']) {
      $summary[] = t('Display with prefix and suffix.');
    }
  }
  return implode('<br />', $summary);
}

/**
 * Implements hook_field_formatter_view().
 */
function formatted_number_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $settings = $display['settings'];
  switch ($display['type']) {
    case 'formatted_number_integer':
    case 'formatted_number_decimal':
      foreach ($items as $delta => $item) {
        $output = format_number($item['value'], $settings['scale']);
        if ($settings['prefix_suffix']) {
          $prefixes = isset($instance['settings']['prefix']) ? array_map('field_filter_xss', explode('|', $instance['settings']['prefix'])) : array(
            '',
          );
          $suffixes = isset($instance['settings']['suffix']) ? array_map('field_filter_xss', explode('|', $instance['settings']['suffix'])) : array(
            '',
          );
          $prefix = count($prefixes) > 1 ? format_plural($item['value'], $prefixes[0], $prefixes[1]) : $prefixes[0];
          $suffix = count($suffixes) > 1 ? format_plural($item['value'], $suffixes[0], $suffixes[1]) : $suffixes[0];
          $output = $prefix . $output . $suffix;
        }
        $element[$delta] = array(
          '#markup' => $output,
        );
      }
      break;
    case 'formatted_number_unformatted':
      foreach ($items as $delta => $item) {
        $element[$delta] = array(
          '#markup' => $item['value'],
        );
      }
      break;
  }
  return $element;
}

/**
 * Implements hook_field_widget_info().
 */
function formatted_number_field_widget_info() {
  return array(
    'formatted_number' => array(
      'label' => t('Numeric text field'),
      'field types' => array_keys(formatted_number_field_info()),
    ),
  );
}

/**
 * Implements hook_field_widget_form().
 */
function formatted_number_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $value = isset($items[$delta]['value']) ? $items[$delta]['value'] : '';

  // Substitute the decimal separator.
  if ($field['type'] == 'formatted_decimal' || $field['type'] == 'formatted_float') {
    $value = strtr($value, '.', format_number_get_options('decimal_point'));
  }
  $decimals = isset($field['settings']['scale']) && (int) $field['settings']['scale'] >= 0 ? (int) $field['settings']['scale'] : 0;
  $element += array(
    '#type' => 'textfield',
    '#default_value' => $value,
    // Allow a slightly larger size that the field length to allow for some
    // configurations where all characters won't fit in input field.
    '#size' => $field['type'] == 'formatted_decimal' ? $field['settings']['precision'] + 4 : $field['settings']['max_length'] + 2,
    // Allow two extra characters for signed values and decimal separator.
    '#maxlength' => $field['type'] == 'formatted_decimal' ? $field['settings']['precision'] + 2 : $field['settings']['max_length'],
    // Extract the number type from the field type name for easier validation.
    '#number_type' => str_replace(array(
      'formatted_',
      '_unsigned',
      'tiny',
      'small',
      'medium',
    ), '', $field['type']),
    '#attributes' => array(
      'class' => array(
        'formatted-number',
      ),
      'decimals' => $decimals,
    ),
    '#attached' => array(
      'css' => array(
        drupal_get_path('module', 'format_number') . '/format_number.css',
        drupal_get_path('module', 'formatted_number') . '/formatted_number.css',
      ),
      'js' => array(
        drupal_get_path('module', 'format_number') . '/format_number.js',
        drupal_get_path('module', 'formatted_number') . '/formatted_number.js',
        array(
          'data' => array(
            'format_number' => format_number_get_options(),
          ),
          'type' => 'setting',
        ),
      ),
    ),
  );

  // Add prefix and suffix.
  if (!empty($instance['settings']['prefix'])) {
    $prefixes = explode('|', $instance['settings']['prefix']);
    $element['#field_prefix'] = field_filter_xss(array_pop($prefixes));
  }
  if (!empty($instance['settings']['suffix'])) {
    $suffixes = explode('|', $instance['settings']['suffix']);
    $element['#field_suffix'] = field_filter_xss(array_pop($suffixes));
  }
  $element['#element_validate'][] = 'formatted_number_field_widget_validate';
  return array(
    'value' => $element,
  );
}

/**
 * FAPI validation of an individual number element.
 */
function formatted_number_field_widget_validate($element, &$form_state) {
  $field = field_widget_field($element, $form_state);
  $instance = field_widget_instance($element, $form_state);
  $type = $element['#number_type'];
  $value = $element['#value'];
  $decimal_separator = format_number_get_options('decimal_point');

  // Reject invalid characters.
  if (!empty($value)) {
    switch ($type) {
      case 'float':
      case 'decimal':
        $regexp = '@([^-0-9\\' . $decimal_separator . '])|(.-)@';
        $message = t('Only numbers and the decimal separator (@separator) allowed in %field.', array(
          '%field' => $instance['label'],
          '@separator' => $decimal_separator,
        ));
        break;
      case 'int':
      case 'integer':
        $regexp = '@([^-0-9])|(.-)@';
        $message = t('Only numbers are allowed in %field.', array(
          '%field' => $instance['label'],
        ));
        break;
    }
    if ($value != preg_replace($regexp, '', $value)) {
      form_error($element, $message);
    }
    else {
      if ($type == 'decimal' || $type == 'float') {

        // Verify that only one decimal separator exists in the field.
        if (substr_count($value, $decimal_separator) > 1) {
          $message = t('%field: There should only be one decimal separator (@separator).', array(
            '%field' => t($instance['label']),
            '@separator' => $decimal_separator,
          ));
          form_error($element, $message);
        }
        else {

          // Substitute the decimal separator; things should be fine.
          $value = strtr($value, $decimal_separator, '.');
        }
      }
      form_set_value($element, $value, $form_state);
    }
  }
}

/**
 * Implements hook_field_widget_error().
 */
function formatted_number_field_widget_error($element, $error, $form, &$form_state) {
  form_error($element['value'], $error['message']);
}