summaryrefslogtreecommitdiff
path: root/modules/field/modules/number/number.module
blob: 15daaa504cc8d58349115fc825e9e0cbedca9698 (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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
<?php
// $Id$

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

/**
 * Implement hook_theme().
 */
function number_theme() {
  return array(
    'number' => array('arguments' => array('element' => NULL)),
    'field_formatter_number_integer' => array('arguments' => array('element' => NULL), 'function' => 'theme_field_formatter_number'),
    'field_formatter_number_decimal' => array('arguments' => array('element' => NULL), 'function' => 'theme_field_formatter_number'),
    'field_formatter_number_unformatted' => array('arguments' => array('element' => NULL)),
  );
}

/**
 * Implement 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' => ' .'),
      'instance_settings' => array('min' => '', 'max' => '', 'prefix' => '', 'suffix' => ''),
      'default_widget' => 'number',
      'default_formatter' => 'number_integer',
    ),
    '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',
      'default_formatter' => 'number_integer',
    ),
  );
}

/**
 * Implement hook_field_schema().
 */
function number_field_schema($field) {
  switch ($field['type']) {
    case 'number_integer' :
      $columns = array(
        'value' => array(
          'type' => 'int',
          'not null' => FALSE
        ),
      );
      break;

    case 'number_float' :
      $columns = array(
        'value' => array(
          'type' => 'float',
          'not null' => FALSE
        ),
      );
      break;

    case 'number_decimal' :
      $columns = array(
        'value' => array(
          'type' => 'numeric',
          'precision' => $field['settings']['precision'],
          'scale' => $field['settings']['scale'],
          'not null' => FALSE
        ),
      );
      break;
  }
  return array(
    'columns' => $columns,
  );
}

/**
 * Implement hook_field_validate().
 *
 * Possible error codes:
 * - 'number_min': The value is smaller than the allowed minimum value.
 * - 'number_max': The value is larger than the allowed maximum value.
 */
function number_field_validate($obj_type, $node, $field, $instance, $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']][$delta][] = array(
          'error' => 'number_min',
          'message' => t('%name: the value may be no smaller 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']][$delta][] = array(
          'error' => 'number_max',
          'message' => t('%name: the value may be no larger than %max.', array('%name' => t($instance['label']), '%max' => $instance['settings']['max'])),
        );
      }
    }
  }
}

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

/**
 * Implement 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,
      ),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
    'number_decimal' => array(
      'label' => t('default'),
      'field types' => array('number_decimal', 'number_float'),
      'settings' =>  array(
        'thousand_separator' => ' ',
        'decimal_separator' => '.',
        'scale' => 2,
        'prefix_suffix' => TRUE,
      ),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
    'number_unformatted' => array(
      'label' => t('unformatted'),
      'field types' => array('number_integer', 'number_decimal', 'number_float'),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
  );
}

/**
 * Theme function for 'unformatted' number field formatter.
 */
function theme_field_formatter_number_unformatted($element) {
  return $element['#item']['value'];
}

/**
 * Proxy theme function for number field formatters.
 */
function theme_field_formatter_number($element) {
  $field = field_info_field($element['#field_name']);
  $instance = field_info_instance($element['#field_name'], $element['#bundle']);
  $value = $element['#item']['value'];
  $settings = $element['#settings'];
  $formatter_type = $element['#formatter'];

  if (empty($value) && $value !== '0') {
    return '';
  }

  $output = number_format($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($value, $prefixes[0], $prefixes[1]) : $prefixes[0];
    $suffix = (count($suffixes) > 1) ? format_plural($value, $suffixes[0], $suffixes[1]) : $suffixes[0];
    $output = $prefix . $output . $suffix;
  }

  return $output;
}

/**
 * Implement hook_field_widget_info().
 *
 * Here we indicate that the Field module will handle
 * multiple values for these widgets.
 *
 * Callbacks can be omitted if default handing is used.
 * They're included here just so this module can be used
 * as an example for custom modules that might do things
 * differently.
 */
function number_field_widget_info() {
  return array(
    'number' => array(
      'label' => t('Text field'),
      'field types' => array('number_integer', 'number_decimal', 'number_float'),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'default value' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
  );
}

/**
 * Implement FAPI hook_elements().
 *
 * Any FAPI callbacks needed for individual widgets can be declared here,
 * and the element will be passed to those callbacks for processing.
 *
 * Drupal will automatically theme the element using a theme with
 * the same name as the hook_elements key.
 *
 * Includes a regex to check for valid values as an additional parameter
 * the validator can use. The regex can be overridden if necessary.
 */
function number_elements() {
  return array(
    'number' => array(
      '#input' => TRUE,
      '#columns' => array('value'), '#delta' => 0,
      '#process' => array('number_process'),
    ),
  );
}

/**
 * Implement hook_field_widget().
 *
 * Attach a single form element to the form. It will be built out and
 * validated in the callback(s) listed in hook_elements. We build it
 * out in the callbacks rather than here in hook_widget so it can be
 * plugged into any module that can provide it with valid
 * $field information.
 *
 * Field module will set the weight, field name and delta values
 * for each form element.
 *
 * If there are multiple values for this field, the Field module will
 * call this function as many times as needed.
 *
 * @param $form
 *   the entire form array, $form['#node'] holds node information
 * @param $form_state
 *   the form_state, $form_state['values'] holds the form values.
 * @param $field
 *   The field structure.
 * @param $instance
 *   the field instance array
 * @param $delta
 *   the order of this item in the array of subelements (0, 1, 2, etc)
 *
 * @return
 *   the form item for a single element for this field
 */
function number_field_widget(&$form, &$form_state, $field, $instance, $items, $delta = 0) {
  $element = array(
    '#type' => $instance['widget']['type'],
    '#default_value' => isset($items[$delta]) ? $items[$delta] : NULL,
  );
  return $element;
}

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

/**
 * Process an individual element.
 *
 * Build the form element. When creating a form using FAPI #process,
 * note that $element['#value'] is already set.
 *
 * The $field and $instance arrays are in $form['#fields'][$element['#field_name']].
 */
function number_process($element, $form_state, $form) {
  $field_name = $element['#field_name'];
  $field = field_info_field($element['#field_name']);
  $instance = field_info_instance($element['#field_name'], $element['#bundle']);
  $field_key  = $element['#columns'][0];

  $value = isset($element['#value'][$field_key]) ? $element['#value'][$field_key] : '';
  if ($field['type'] == 'number_decimal') {
    $value = str_replace('.', $field['settings']['decimal'], $value);
  }

  $element[$field_key] = array(
    '#type' => 'textfield',
    '#default_value' => $value,
    // Need to 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'] + 2 : 12,
    '#maxlength' => $field['type'] == 'number_decimal' ? $field['settings']['precision'] : 10,
    '#attributes' => array('class' => 'number'),
    // The following values were set by the Field module and need
    // to be passed down to the nested element.
    '#title' => $element['#title'],
    '#description' => $element['#description'],
    '#required' => $element['#required'],
    '#field_name' => $element['#field_name'],
    '#bundle' => $element['#bundle'],
    '#delta' => $element['#delta'],
    '#columns' => $element['#columns'],
  );

  if (!empty($instance['settings']['prefix'])) {
    $prefixes = explode('|', $instance['settings']['prefix']);
    $element[$field_key]['#field_prefix'] = field_filter_xss(array_pop($prefixes));
  }
  if (!empty($instance['settings']['suffix'])) {
    $suffixes = explode('|', $instance['settings']['suffix']);
    $element[$field_key]['#field_suffix'] = field_filter_xss(array_pop($suffixes));
  }

  // Make sure we don't wipe out element validation added elsewhere.
  if (empty($element['#element_validate'])) {
    $element['#element_validate'] = array();
  }
  switch ($field['type']) {
    case 'number_float':
      $element['#element_validate'][] = 'number_float_validate';
      break;
    case 'number_integer':
      $element['#element_validate'][] = 'number_integer_validate';
      break;
    case 'number_decimal':
      $element['#element_validate'][] = 'number_decimal_validate';
      break;
  }

  return $element;
}

/**
 * FAPI validation of an individual float element.
 */
function number_float_validate($element, &$form_state) {
  $field = field_info_field($element['#field_name']);
  $instance = field_info_instance($element['#field_name'], $element['#bundle']);
  $field_key = $element['#columns'][0];
  $value = $element['#value'][$field_key];

  if (($element[$field_key]['#required'] || !empty($value))) {
    $start = $value;
    $value = preg_replace('@[^-0-9\.]@', '', $value);
    if ($start != $value) {
      $error_field = implode('][', $element['#parents']) . '][' . $field_key;
      form_set_error($error_field, t('Only numbers and decimals are allowed in %field.', array('%field' => t($instance['label']))));
    }
    else {
      form_set_value($element[$field_key], $value, $form_state);
    }
  }
}

/**
 * FAPI validation of an individual integer element.
 */
function number_integer_validate($element, &$form_state) {
  $field = field_info_field($element['#field_name']);
  $instance = field_info_instance($element['#field_name'], $element['#bundle']);
  $field_key = $element['#columns'][0];
  $value = $element['#value'][$field_key];

  if (($element[$field_key]['#required'] || !empty($value))) {
    $start = $value;
    $value = preg_replace('@[^-0-9]@', '', $value);
    if ($start != $value) {
      $error_field = implode('][', $element['#parents']) . '][' . $field_key;
      form_set_error($error_field, t('Only numbers are allowed in %field.', array('%field' => t($instance['label']))));
    }
    else {
      form_set_value($element[$field_key], $value, $form_state);
    }
  }
}

/**
 * FAPI validation of an individual decimal element.
 */
function number_decimal_validate($element, &$form_state) {
  $field = field_info_field($element['#field_name']);
  $instance = field_info_instance($element['#field_name'], $element['#bundle']);
  $field_key = $element['#columns'][0];
  $value = $element['#value'][$field_key];

  if (($element[$field_key]['#required'] || !empty($value))) {
    $start = $value;
    $value = preg_replace('@[^-0-9\\' . $field['settings']['decimal'] . ']@', '', $value);
    if ($start != $value) {
      $error_field = implode('][', $element['#parents']) . '][' . $field_key;
      form_set_error($error_field, t('Only numbers and the decimal character (%decimal) are allowed in %field.', array('%decimal' => $field['settings']['decimal'], '%field' => t($instance['label']))));
    }
    else {
      $value = str_replace($field['settings']['decimal'], ' .', $value);
      $value = round($value, $field['settings']['scale']);
      form_set_value($element[$field_key], $value, $form_state);
    }
  }
}

/**
 * FAPI theme for an individual number element.
 *
 * The textfield is already rendered by the textfield
 * theme and the HTML output lives in $element['#children'].
 * Override this theme to make custom changes to the output.
 *
 * $element['#field_name'] contains the field name
 * $element['#delta] is the position of this element in the group
 */
function theme_number($element) {
  return $element['#children'];
}