number.module 12.4 KB
Newer Older
1 2 3 4 5 6 7
<?php

/**
 * @file
 * Defines numeric field types.
 */

8 9 10 11 12 13 14 15 16 17 18 19 20
/**
 * Implements hook_help().
 */
function number_help($path, $arg) {
  switch ($path) {
    case 'admin/help#number':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The Number module defines various numeric field types for the Field module. Numbers can be in integer, decimal, or floating-point form, and they can be formatted 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;
  }
}

21
/**
22
 * Implements hook_field_info().
23 24 25 26 27 28 29 30
 */
function number_field_info() {
  return array(
    'number_integer' => array(
      'label' => t('Integer'),
      'description' => t('This field stores a number in the database as an integer.'),
      'instance_settings' => array('min' => '', 'max' => '', 'prefix' => '', 'suffix' => ''),
      'default_widget' => 'number',
31
      'default_formatter' => 'number_integer',
32 33 34 35
    ),
    'number_decimal' => array(
      'label' => t('Decimal'),
      'description' => t('This field stores a number in the database in a fixed decimal format.'),
36
      'settings' => array('precision' => 10, 'scale' => 2),
37 38
      'instance_settings' => array('min' => '', 'max' => '', 'prefix' => '', 'suffix' => ''),
      'default_widget' => 'number',
39
      'default_formatter' => 'number_decimal',
40 41 42 43 44 45
    ),
    'number_float' => array(
      'label' => t('Float'),
      'description' => t('This field stores a number in the database in a floating point format.'),
      'instance_settings' => array('min' => '', 'max' => '', 'prefix' => '', 'suffix' => ''),
      'default_widget' => 'number',
46
      'default_formatter' => 'number_decimal',
47 48 49 50
    ),
  );
}

51
/**
52
 * Implements hook_field_settings_form().
53
 */
54
function number_field_settings_form($field, $instance, $has_data) {
55 56 57 58 59 60 61 62 63 64
  $settings = $field['settings'];
  $form = array();

  if ($field['type'] == 'number_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.'),
65
      '#disabled' => $has_data,
66 67 68 69 70 71 72
    );
    $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.'),
73
      '#disabled' => $has_data,
74
    );
75
  }
76 77 78 79 80

  return $form;
}

/**
81
 * Implements hook_field_instance_settings_form().
82 83 84 85 86 87 88 89 90
 */
function 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.'),
91
    '#element_validate' => array('form_validate_number'),
92 93 94 95 96 97
  );
  $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.'),
98
    '#element_validate' => array('form_validate_number'),
99 100 101 102 103 104 105 106 107 108 109 110 111
  );
  $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,
112
    '#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')."),
113 114 115 116 117
  );

  return $form;
}

118
/**
119
 * Implements hook_field_validate().
120 121
 *
 * Possible error codes:
122 123
 * - 'number_min': The value is less than the allowed minimum value.
 * - 'number_max': The value is greater than the allowed maximum value.
124
 */
125
function number_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
126 127 128
  foreach ($items as $delta => $item) {
    if ($item['value'] != '') {
      if (is_numeric($instance['settings']['min']) && $item['value'] < $instance['settings']['min']) {
129
        $errors[$field['field_name']][$langcode][$delta][] = array(
130
          'error' => 'number_min',
131
          'message' => t('%name: the value may be no less than %min.', array('%name' => $instance['label'], '%min' => $instance['settings']['min'])),
132 133 134
        );
      }
      if (is_numeric($instance['settings']['max']) && $item['value'] > $instance['settings']['max']) {
135
        $errors[$field['field_name']][$langcode][$delta][] = array(
136
          'error' => 'number_max',
137
          'message' => t('%name: the value may be no greater than %max.', array('%name' => $instance['label'], '%max' => $instance['settings']['max'])),
138
        );
139 140 141 142 143
      }
    }
  }
}

144 145 146
/**
 * Implements hook_field_presave().
 */
147
function number_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
148 149 150 151 152 153 154 155 156 157 158
  if ($field['type'] == 'number_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']);
      }
    }
  }
}

159
/**
160
 * Implements hook_field_is_empty().
161 162
 */
function number_field_is_empty($item, $field) {
163
  if (empty($item['value']) && (string) $item['value'] !== '0') {
164 165 166 167 168 169
    return TRUE;
  }
  return FALSE;
}

/**
170
 * Implements hook_field_formatter_info().
171 172 173
 */
function number_field_formatter_info() {
  return array(
174 175 176
    // The 'Default' formatter is different for integer fields on the one hand,
    // and for decimal and float fields on the other hand, in order to be able
    // to use different default values for the settings.
177
    'number_integer' => array(
178
      'label' => t('Default'),
179 180
      'field types' => array('number_integer'),
      'settings' =>  array(
181
        'thousand_separator' => '',
182 183 184 185
        // The 'decimal_separator' and 'scale' settings are not configurable
        // through the UI, and will therefore keep their default values. They
        // are only present so that the 'number_integer' and 'number_decimal'
        // formatters can use the same code.
186 187 188 189 190 191
        'decimal_separator' => '.',
        'scale' => 0,
        'prefix_suffix' => TRUE,
      ),
    ),
    'number_decimal' => array(
192
      'label' => t('Default'),
193 194
      'field types' => array('number_decimal', 'number_float'),
      'settings' =>  array(
195
        'thousand_separator' => '',
196 197 198 199 200 201
        'decimal_separator' => '.',
        'scale' => 2,
        'prefix_suffix' => TRUE,
      ),
    ),
    'number_unformatted' => array(
202
      'label' => t('Unformatted'),
203 204 205 206 207
      'field types' => array('number_integer', 'number_decimal', 'number_float'),
    ),
  );
}

208 209 210 211 212 213 214
/**
 * Implements hook_field_formatter_settings_form().
 */
function number_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

215 216 217 218 219 220
  if ($display['type'] == 'number_decimal' || $display['type'] == 'number_integer') {
    $options = array(
      ''  => t('<none>'),
      '.' => t('Decimal point'),
      ',' => t('Comma'),
      ' ' => t('Space'),
221 222
      chr(8201) => t('Thin space'),
      "'" => t('Apostrophe'),
223
    );
224
    $element['thousand_separator'] = array(
225
      '#type' => 'select',
226 227 228
      '#title' => t('Thousand marker'),
      '#options' => $options,
      '#default_value' => $settings['thousand_separator'],
229 230
    );

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
    if ($display['type'] == 'number_decimal') {
      $element['decimal_separator'] = array(
        '#type' => 'select',
        '#title' => t('Decimal marker'),
        '#options' => array('.' => t('Decimal point'), ',' => t('Comma')),
        '#default_value' => $settings['decimal_separator'],
      );
      $element['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.'),
      );
    }

    $element['prefix_suffix'] = array(
      '#type' => 'checkbox',
      '#title' => t('Display prefix and suffix.'),
      '#default_value' => $settings['prefix_suffix'],
    );
  }
253

254
  return $element;
255 256 257 258 259 260 261 262 263 264
}

/**
 * Implements hook_field_formatter_settings_summary().
 */
function number_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  $summary = array();
265 266 267 268 269
  if ($display['type'] == 'number_decimal' || $display['type'] == 'number_integer') {
    $summary[] = number_format(1234.1234567890, $settings['scale'], $settings['decimal_separator'], $settings['thousand_separator']);
    if ($settings['prefix_suffix']) {
      $summary[] = t('Display with prefix and suffix.');
    }
270 271 272 273 274
  }

  return implode('<br />', $summary);
}

275
/**
276
 * Implements hook_field_formatter_view().
277
 */
278
function number_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
279 280
  $element = array();
  $settings = $display['settings'];
281

282 283 284
  switch ($display['type']) {
    case 'number_integer':
    case 'number_decimal':
285 286 287 288 289 290 291 292 293 294
      foreach ($items as $delta => $item) {
        $output = number_format($item['value'], $settings['scale'], $settings['decimal_separator'], $settings['thousand_separator']);
        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);
295 296
      }
      break;
297

298
    case 'number_unformatted':
299 300 301
      foreach ($items as $delta => $item) {
        $element[$delta] = array('#markup' => $item['value']);
      }
302
      break;
303 304
  }

305
  return $element;
306 307 308
}

/**
309
 * Implements hook_field_widget_info().
310 311 312 313 314 315 316 317 318 319 320
 */
function number_field_widget_info() {
  return array(
    'number' => array(
      'label' => t('Text field'),
      'field types' => array('number_integer', 'number_decimal', 'number_float'),
    ),
  );
}

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

326
  $element += array(
327
    '#type' => 'number',
328 329 330
    '#default_value' => $value,
  );

331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
  // Set the step for floating point and decimal numbers.
  switch ($field['type']) {
    case 'number_decimal':
      $element['#step'] = pow(0.1, $field['settings']['scale']);
      break;

    case 'number_float':
      $element['#step'] = 'any';
      break;
  }

  // Set minimum and maximum.
  if (is_numeric($instance['settings']['min'])) {
    $element['#min'] = $instance['settings']['min'];
  }
  if (is_numeric($instance['settings']['max'])) {
    $element['#max'] = $instance['settings']['max'];
  }

350
  // Add prefix and suffix.
351 352
  if (!empty($instance['settings']['prefix'])) {
    $prefixes = explode('|', $instance['settings']['prefix']);
353
    $element['#field_prefix'] = field_filter_xss(array_pop($prefixes));
354 355 356
  }
  if (!empty($instance['settings']['suffix'])) {
    $suffixes = explode('|', $instance['settings']['suffix']);
357
    $element['#field_suffix'] = field_filter_xss(array_pop($suffixes));
358 359
  }

360
  return array('value' => $element);
361 362 363
}

/**
364
 * Implements hook_field_widget_error().
365
 */
366
function number_field_widget_error($element, $error, $form, &$form_state) {
367
  form_error($element['value'], $error['message']);
368
}