summaryrefslogtreecommitdiff
path: root/modules/field/modules/number/number.module
blob: 45ea95455e2f0d5be1571f350ae9cdcf77996a9e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
<?php
// $Id$

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

/**
 * 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;
  }
}

/**
 * Implements hook_field_info().
 */
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',
      'default_formatter' => 'number_integer',
    ),
    'number_decimal' => array(
      'label' => t('Decimal'),
      'description' => t('This field stores a number in the database in a fixed decimal format.'),
      'settings' => array('precision' => 10, 'scale' => 2, 'decimal_separator' => '.'),
      'instance_settings' => array('min' => '', 'max' => '', 'prefix' => '', 'suffix' => ''),
      'default_widget' => 'number',
      'default_formatter' => 'number_decimal',
    ),
    'number_float' => array(
      'label' => t('Float'),
      'description' => t('This field stores a number in the database in a floating point format.'),
      'settings' => array('decimal_separator' => '.'),
      'instance_settings' => array('min' => '', 'max' => '', 'prefix' => '', 'suffix' => ''),
      'default_widget' => 'number',
      'default_formatter' => 'number_decimal',
    ),
  );
}

/**
 * Implements hook_field_settings_form().
 */
function number_field_settings_form($field, $instance, $has_data) {
  $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.'),
      '#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,
    );
  }
  if ($field['type'] == 'number_decimal' || $field['type'] == 'number_float') {
    $form['decimal_separator'] = array(
      '#type' => 'select',
      '#title' => t('Decimal marker'),
      '#options' => array('.' => t('Decimal point'), ',' => t('Comma')),
      '#default_value' => $settings['decimal_separator'],
      '#description' => t('The character users will input to mark the decimal point in forms.'),
    );
  }

  return $form;
}

/**
 * Implements hook_field_instance_settings_form().
 */
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.'),
    '#element_validate' => array('_element_validate_number'),
  );
  $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_number'),
  );
  $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;
}

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

/**
 * Implements hook_field_presave().
 */
function number_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  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']);
      }
    }
  }
}

/**
 * Implements hook_field_is_empty().
 */
function number_field_is_empty($item, $field) {
  if (empty($item['value']) && (string) $item['value'] !== '0') {
    return TRUE;
  }
  return FALSE;
}

/**
 * Implements hook_field_formatter_info().
 */
function number_field_formatter_info() {
  return array(
    'number_integer' => array(
      'label' => t('Default'),
      'field types' => array('number_integer'),
      'settings' =>  array(
        'thousand_separator' => ' ',
        'decimal_separator' => '.',
        'scale' => 0,
        'prefix_suffix' => TRUE,
      ),
    ),
    'number_decimal' => array(
      'label' => t('Default'),
      'field types' => array('number_decimal', 'number_float'),
      'settings' =>  array(
        'thousand_separator' => ' ',
        'decimal_separator' => '.',
        'scale' => 2,
        'prefix_suffix' => TRUE,
      ),
    ),
    'number_unformatted' => array(
      'label' => t('Unformatted'),
      'field types' => array('number_integer', 'number_decimal', 'number_float'),
    ),
  );
}

/**
 * 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'];

  $options = array(
    ''  => t('<none>'),
    '.' => t('Decimal point'),
    ',' => t('Comma'),
    ' ' => t('Space'),
  );
  $element['thousand_separator'] = array(
    '#type' => 'select',
    '#title' => t('Thousand marker'),
    '#options' => $options,
    '#default_value' => $settings['thousand_separator'],
  );

  if ($display['type'] == 'number_decimal' || $display['type'] == 'number_float') {
    $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'],
  );

  return $element;
}

/**
 * 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();
  $summary[] = number_format(1234.1234567890, $settings['scale'], $settings['decimal_separator'], $settings['thousand_separator']);
  if ($settings['prefix_suffix']) {
    $summary[] = t('Display with prefix and suffix.');
  }

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

/**
 * Implements hook_field_formatter_view().
 */
function number_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $settings = $display['settings'];

  switch ($display['type']) {
    case 'number_integer':
    case 'number_decimal':
      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);
      }
      break;

    case 'number_unformatted':
      foreach ($items as $delta => $item) {
        $element[$delta] = array('#markup' => $item['value']);
      }
      break;
  }

  return $element;
}

/**
 * Implements hook_field_widget_info().
 */
function number_field_widget_info() {
  return array(
    'number' => array(
      'label' => t('Text field'),
      'field types' => array('number_integer', 'number_decimal', 'number_float'),
    ),
  );
}

/**
 * Implements hook_field_widget_form().
 */
function 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'] == 'number_decimal' || $field['type'] == 'number_float') {
    $value = strtr($value, '.', $field['settings']['decimal_separator']);
  }

  $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'] == 'number_decimal' ? $field['settings']['precision'] + 4 : 12,
    // Allow two extra characters for signed values and decimal separator.
    '#maxlength' => $field['type'] == 'number_decimal' ? $field['settings']['precision'] + 2 : 10,
    // Extract the number type from the field type name for easier validation.
    '#number_type' => str_replace('number_', '', $field['type']),
  );

  // 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'][] = 'number_field_widget_validate';

  return array('value' => $element);
}

/**
 * FAPI validation of an individual number element.
 */
function 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'];

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

      case 'integer':
        $regexp = '@[^-0-9]@';
        $message = t('Only numbers are allowed in %field.', array('%field' => t($instance['label'])));
        break;
    }
    if ($value != preg_replace($regexp, '', $value)) {
      form_error($element, $message);
    }
    else {
      // Substitute the decimal separator,
      if ($type == 'decimal' || $type == 'float') {
        $value = strtr($value, $field['settings']['decimal_separator'], '.');
      }
      form_set_value($element, $value, $form_state);
    }
  }
}

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