Projet

Général

Profil

Paste
Télécharger (15,2 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / field / modules / number / number.module @ c7768a53

1
<?php
2

    
3
/**
4
 * @file
5
 * Defines numeric field types.
6
 */
7

    
8
/**
9
 * Implements hook_help().
10
 */
11
function number_help($path, $arg) {
12
  switch ($path) {
13
    case 'admin/help#number':
14
      $output = '';
15
      $output .= '<h3>' . t('About') . '</h3>';
16
      $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>';
17
      return $output;
18
  }
19
}
20

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

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

    
59
  if ($field['type'] == 'number_decimal') {
60
    $form['precision'] = array(
61
      '#type' => 'select',
62
      '#title' => t('Precision'),
63
      '#options' => drupal_map_assoc(range(10, 32)),
64
      '#default_value' => $settings['precision'],
65
      '#description' => t('The total number of digits to store in the database, including those to the right of the decimal.'),
66
      '#disabled' => $has_data,
67
    );
68
    $form['scale'] = array(
69
      '#type' => 'select',
70
      '#title' => t('Scale'),
71
      '#options' => drupal_map_assoc(range(0, 10)),
72
      '#default_value' => $settings['scale'],
73
      '#description' => t('The number of digits to the right of the decimal.'),
74
      '#disabled' => $has_data,
75
    );
76
  }
77
  if ($field['type'] == 'number_decimal' || $field['type'] == 'number_float') {
78
    $form['decimal_separator'] = array(
79
      '#type' => 'select',
80
      '#title' => t('Decimal marker'),
81
      '#options' => array('.' => t('Decimal point'), ',' => t('Comma')),
82
      '#default_value' => $settings['decimal_separator'],
83
      '#description' => t('The character users will input to mark the decimal point in forms.'),
84
    );
85
  }
86

    
87
  return $form;
88
}
89

    
90
/**
91
 * Implements hook_field_instance_settings_form().
92
 */
93
function number_field_instance_settings_form($field, $instance) {
94
  $settings = $instance['settings'];
95

    
96
  $form['min'] = array(
97
    '#type' => 'textfield',
98
    '#title' => t('Minimum'),
99
    '#default_value' => $settings['min'],
100
    '#description' => t('The minimum value that should be allowed in this field. Leave blank for no minimum.'),
101
    '#element_validate' => array('element_validate_number'),
102
  );
103
  $form['max'] = array(
104
    '#type' => 'textfield',
105
    '#title' => t('Maximum'),
106
    '#default_value' => $settings['max'],
107
    '#description' => t('The maximum value that should be allowed in this field. Leave blank for no maximum.'),
108
    '#element_validate' => array('element_validate_number'),
109
  );
110
  $form['prefix'] = array(
111
    '#type' => 'textfield',
112
    '#title' => t('Prefix'),
113
    '#default_value' => $settings['prefix'],
114
    '#size' => 60,
115
    '#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')."),
116
  );
117
  $form['suffix'] = array(
118
    '#type' => 'textfield',
119
    '#title' => t('Suffix'),
120
    '#default_value' => $settings['suffix'],
121
    '#size' => 60,
122
    '#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')."),
123
  );
124

    
125
  return $form;
126
}
127

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

    
154
/**
155
 * Implements hook_field_presave().
156
 */
157
function number_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
158
  if ($field['type'] == 'number_decimal') {
159
    // Let PHP round the value to ensure consistent behavior across storage
160
    // backends.
161
    foreach ($items as $delta => $item) {
162
      if (isset($item['value'])) {
163
        $items[$delta]['value'] = round($item['value'], $field['settings']['scale']);
164
      }
165
    }
166
  }
167
  if ($field['type'] == 'number_float') {
168
    // Remove the decimal point from float values with decimal
169
    // point but no decimal numbers.
170
    foreach ($items as $delta => $item) {
171
      if (isset($item['value'])) {
172
        $items[$delta]['value'] = floatval($item['value']);
173
      }
174
    }
175
  }
176
}
177

    
178
/**
179
 * Implements hook_field_is_empty().
180
 */
181
function number_field_is_empty($item, $field) {
182
  if (empty($item['value']) && (string) $item['value'] !== '0') {
183
    return TRUE;
184
  }
185
  return FALSE;
186
}
187

    
188
/**
189
 * Implements hook_field_formatter_info().
190
 */
191
function number_field_formatter_info() {
192
  return array(
193
    // The 'Default' formatter is different for integer fields on the one hand,
194
    // and for decimal and float fields on the other hand, in order to be able
195
    // to use different default values for the settings.
196
    'number_integer' => array(
197
      'label' => t('Default'),
198
      'field types' => array('number_integer'),
199
      'settings' =>  array(
200
        'thousand_separator' => '',
201
        // The 'decimal_separator' and 'scale' settings are not configurable
202
        // through the UI, and will therefore keep their default values. They
203
        // are only present so that the 'number_integer' and 'number_decimal'
204
        // formatters can use the same code.
205
        'decimal_separator' => '.',
206
        'scale' => 0,
207
        'prefix_suffix' => TRUE,
208
      ),
209
    ),
210
    'number_decimal' => array(
211
      'label' => t('Default'),
212
      'field types' => array('number_decimal', 'number_float'),
213
      'settings' =>  array(
214
        'thousand_separator' => '',
215
        'decimal_separator' => '.',
216
        'scale' => 2,
217
        'prefix_suffix' => TRUE,
218
      ),
219
    ),
220
    'number_unformatted' => array(
221
      'label' => t('Unformatted'),
222
      'field types' => array('number_integer', 'number_decimal', 'number_float'),
223
    ),
224
  );
225
}
226

    
227
/**
228
 * Implements hook_field_formatter_settings_form().
229
 */
230
function number_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
231
  $display = $instance['display'][$view_mode];
232
  $settings = $display['settings'];
233

    
234
  $element = array();
235

    
236
  if ($display['type'] == 'number_decimal' || $display['type'] == 'number_integer') {
237
    $options = array(
238
      ''  => t('<none>'),
239
      '.' => t('Decimal point'),
240
      ',' => t('Comma'),
241
      ' ' => t('Space'),
242
    );
243
    $element['thousand_separator'] = array(
244
      '#type' => 'select',
245
      '#title' => t('Thousand marker'),
246
      '#options' => $options,
247
      '#default_value' => $settings['thousand_separator'],
248
    );
249

    
250
    if ($display['type'] == 'number_decimal') {
251
      $element['decimal_separator'] = array(
252
        '#type' => 'select',
253
        '#title' => t('Decimal marker'),
254
        '#options' => array('.' => t('Decimal point'), ',' => t('Comma')),
255
        '#default_value' => $settings['decimal_separator'],
256
      );
257
      $element['scale'] = array(
258
        '#type' => 'select',
259
        '#title' => t('Scale'),
260
        '#options' => drupal_map_assoc(range(0, 10)),
261
        '#default_value' => $settings['scale'],
262
        '#description' => t('The number of digits to the right of the decimal.'),
263
      );
264
    }
265

    
266
    $element['prefix_suffix'] = array(
267
      '#type' => 'checkbox',
268
      '#title' => t('Display prefix and suffix.'),
269
      '#default_value' => $settings['prefix_suffix'],
270
    );
271
  }
272

    
273
  return $element;
274
}
275

    
276
/**
277
 * Implements hook_field_formatter_settings_summary().
278
 */
279
function number_field_formatter_settings_summary($field, $instance, $view_mode) {
280
  $display = $instance['display'][$view_mode];
281
  $settings = $display['settings'];
282

    
283
  $summary = array();
284
  if ($display['type'] == 'number_decimal' || $display['type'] == 'number_integer') {
285
    $summary[] = number_format(1234.1234567890, $settings['scale'], $settings['decimal_separator'], $settings['thousand_separator']);
286
    if ($settings['prefix_suffix']) {
287
      $summary[] = t('Display with prefix and suffix.');
288
    }
289
  }
290

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

    
294
/**
295
 * Implements hook_field_formatter_view().
296
 */
297
function number_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
298
  $element = array();
299
  $settings = $display['settings'];
300

    
301
  switch ($display['type']) {
302
    case 'number_integer':
303
    case 'number_decimal':
304
      foreach ($items as $delta => $item) {
305
        $output = number_format($item['value'], $settings['scale'], $settings['decimal_separator'], $settings['thousand_separator']);
306
        if ($settings['prefix_suffix']) {
307
          $prefixes = isset($instance['settings']['prefix']) ? array_map('field_filter_xss', explode('|', $instance['settings']['prefix'])) : array('');
308
          $suffixes = isset($instance['settings']['suffix']) ? array_map('field_filter_xss', explode('|', $instance['settings']['suffix'])) : array('');
309
          $prefix = (count($prefixes) > 1) ? format_plural($item['value'], $prefixes[0], $prefixes[1]) : $prefixes[0];
310
          $suffix = (count($suffixes) > 1) ? format_plural($item['value'], $suffixes[0], $suffixes[1]) : $suffixes[0];
311
          $output = $prefix . $output . $suffix;
312
        }
313
        $element[$delta] = array('#markup' => $output);
314
      }
315
      break;
316

    
317
    case 'number_unformatted':
318
      foreach ($items as $delta => $item) {
319
        $element[$delta] = array('#markup' => $item['value']);
320
      }
321
      break;
322
  }
323

    
324
  return $element;
325
}
326

    
327
/**
328
 * Implements hook_field_widget_info().
329
 */
330
function number_field_widget_info() {
331
  return array(
332
    'number' => array(
333
      'label' => t('Text field'),
334
      'field types' => array('number_integer', 'number_decimal', 'number_float'),
335
    ),
336
  );
337
}
338

    
339
/**
340
 * Implements hook_field_widget_form().
341
 */
342
function number_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
343
  $value = isset($items[$delta]['value']) ? $items[$delta]['value'] : '';
344
  // Substitute the decimal separator.
345
  if ($field['type'] == 'number_decimal' || $field['type'] == 'number_float') {
346
    $value = strtr($value, '.', $field['settings']['decimal_separator']);
347
  }
348

    
349
  $element += array(
350
    '#type' => 'textfield',
351
    '#default_value' => $value,
352
    // Allow a slightly larger size that the field length to allow for some
353
    // configurations where all characters won't fit in input field.
354
    '#size' => $field['type'] == 'number_decimal' ? $field['settings']['precision'] + 4 : 12,
355
    // Allow two extra characters for signed values and decimal separator.
356
    '#maxlength' => $field['type'] == 'number_decimal' ? $field['settings']['precision'] + 2 : 10,
357
    // Extract the number type from the field type name for easier validation.
358
    '#number_type' => str_replace('number_', '', $field['type']),
359
  );
360

    
361
  // Add prefix and suffix.
362
  if (!empty($instance['settings']['prefix'])) {
363
    $prefixes = explode('|', $instance['settings']['prefix']);
364
    $element['#field_prefix'] = field_filter_xss(array_pop($prefixes));
365
  }
366
  if (!empty($instance['settings']['suffix'])) {
367
    $suffixes = explode('|', $instance['settings']['suffix']);
368
    $element['#field_suffix'] = field_filter_xss(array_pop($suffixes));
369
  }
370

    
371
  $element['#element_validate'][] = 'number_field_widget_validate';
372

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

    
376
/**
377
 * FAPI validation of an individual number element.
378
 */
379
function number_field_widget_validate($element, &$form_state) {
380
  $field = field_widget_field($element, $form_state);
381
  $instance = field_widget_instance($element, $form_state);
382

    
383
  $type = $element['#number_type'];
384
  $value = $element['#value'];
385

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

    
395
      case 'integer':
396
        $regexp = '@([^-0-9])|(.-)@';
397
        $message = t('Only numbers are allowed in %field.', array('%field' => $instance['label']));
398
        break;
399
    }
400
    if ($value != preg_replace($regexp, '', $value)) {
401
      form_error($element, $message);
402
    }
403
    else {
404
      if ($type == 'decimal' || $type == 'float') {
405
        // Verify that only one decimal separator exists in the field.
406
        if (substr_count($value, $field['settings']['decimal_separator']) > 1) {
407
          $message = t('%field: There should only be one decimal separator (@separator).',
408
            array(
409
              '%field' => t($instance['label']),
410
              '@separator' => $field['settings']['decimal_separator'],
411
            )
412
          );
413
          form_error($element, $message);
414
        }
415
        else {
416
          // Substitute the decimal separator; things should be fine.
417
          $value = strtr($value, $field['settings']['decimal_separator'], '.');
418
        }
419
      }
420
      form_set_value($element, $value, $form_state);
421
    }
422
  }
423
}
424

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