Project

General

Profile

Paste
Download (17.2 KB) Statistics
| Branch: | Revision:

root / drupal7 / modules / field / modules / list / list.module @ db2d93dd

1
<?php
2

    
3
/**
4
 * @file
5
 * Defines list field types that can be used with the Options module.
6
 */
7

    
8
/**
9
 * Implements hook_help().
10
 */
11
function list_help($path, $arg) {
12
  switch ($path) {
13
    case 'admin/help#list':
14
      $output = '';
15
      $output .= '<h3>' . t('About') . '</h3>';
16
      $output .= '<p>' . t('The List module defines various fields for storing a list of items, for use with the Field module. Usually these items are entered through a select list, checkboxes, or radio buttons. 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 list_field_info() {
25
  return array(
26
    'list_integer' => array(
27
      'label' => t('List (integer)'),
28
      'description' => t("This field stores integer values from a list of allowed 'value => label' pairs, i.e. 'Lifetime in days': 1 => 1 day, 7 => 1 week, 31 => 1 month."),
29
      'settings' => array('allowed_values' => array(), 'allowed_values_function' => ''),
30
      'default_widget' => 'options_select',
31
      'default_formatter' => 'list_default',
32
    ),
33
    'list_float' => array(
34
      'label' => t('List (float)'),
35
      'description' => t("This field stores float values from a list of allowed 'value => label' pairs, i.e. 'Fraction': 0 => 0, .25 => 1/4, .75 => 3/4, 1 => 1."),
36
      'settings' => array('allowed_values' => array(), 'allowed_values_function' => ''),
37
      'default_widget' => 'options_select',
38
      'default_formatter' => 'list_default',
39
    ),
40
    'list_text' => array(
41
      'label' => t('List (text)'),
42
      'description' => t("This field stores text values from a list of allowed 'value => label' pairs, i.e. 'US States': IL => Illinois, IA => Iowa, IN => Indiana."),
43
      'settings' => array('allowed_values' => array(), 'allowed_values_function' => ''),
44
      'default_widget' => 'options_select',
45
      'default_formatter' => 'list_default',
46
    ),
47
    'list_boolean' => array(
48
      'label' => t('Boolean'),
49
      'description' => t('This field stores simple on/off or yes/no options.'),
50
      'settings' => array('allowed_values' => array(), 'allowed_values_function' => ''),
51
      'default_widget' => 'options_buttons',
52
      'default_formatter' => 'list_default',
53
    ),
54
  );
55
}
56

    
57
/**
58
 * Implements hook_field_settings_form().
59
 */
60
function list_field_settings_form($field, $instance, $has_data) {
61
  $settings = $field['settings'];
62

    
63
  switch ($field['type']) {
64
    case 'list_integer':
65
    case 'list_float':
66
    case 'list_text':
67
      $form['allowed_values'] = array(
68
        '#type' => 'textarea',
69
        '#title' => t('Allowed values list'),
70
        '#default_value' => list_allowed_values_string($settings['allowed_values']),
71
        '#rows' => 10,
72
        '#element_validate' => array('list_allowed_values_setting_validate'),
73
        '#field_has_data' => $has_data,
74
        '#field' => $field,
75
        '#field_type' => $field['type'],
76
        '#access' => empty($settings['allowed_values_function']),
77
      );
78

    
79
      $description = '<p>' . t('The possible values this field can contain. Enter one value per line, in the format key|label.');
80
      if ($field['type'] == 'list_integer' || $field['type'] == 'list_float') {
81
        $description .= '<br/>' . t('The key is the stored value, and must be numeric. The label will be used in displayed values and edit forms.');
82
        $description .= '<br/>' . t('The label is optional: if a line contains a single number, it will be used as key and label.');
83
        $description .= '<br/>' . t('Lists of labels are also accepted (one label per line), only if the field does not hold any values yet. Numeric keys will be automatically generated from the positions in the list.');
84
      }
85
      else {
86
        $description .= '<br/>' . t('The key is the stored value. The label will be used in displayed values and edit forms.');
87
        $description .= '<br/>' . t('The label is optional: if a line contains a single string, it will be used as key and label.');
88
      }
89
      $description .= '</p>';
90
      $form['allowed_values']['#description'] = $description;
91

    
92
      break;
93

    
94
    case 'list_boolean':
95
      $values = $settings['allowed_values'];
96
      $off_value = array_shift($values);
97
      $on_value = array_shift($values);
98

    
99
      $form['allowed_values'] = array(
100
        '#type' => 'value',
101
        '#description' => '',
102
        '#value_callback' => 'list_boolean_allowed_values_callback',
103
        '#access' => empty($settings['allowed_values_function']),
104
      );
105
      $form['allowed_values']['on'] = array(
106
        '#type' => 'textfield',
107
        '#title' => t('On value'),
108
        '#default_value' => $on_value,
109
        '#required' => FALSE,
110
        '#description' => t('If left empty, "1" will be used.'),
111
        // Change #parents to make sure the element is not saved into field
112
        // settings.
113
        '#parents' => array('on'),
114
      );
115
      $form['allowed_values']['off'] = array(
116
        '#type' => 'textfield',
117
        '#title' => t('Off value'),
118
        '#default_value' => $off_value,
119
        '#required' => FALSE,
120
        '#description' => t('If left empty, "0" will be used.'),
121
        // Change #parents to make sure the element is not saved into field
122
        // settings.
123
        '#parents' => array('off'),
124
      );
125

    
126
      // Link the allowed value to the on / off elements to prepare for the rare
127
      // case of an alter changing #parents.
128
      $form['allowed_values']['#on_parents'] = &$form['allowed_values']['on']['#parents'];
129
      $form['allowed_values']['#off_parents'] = &$form['allowed_values']['off']['#parents'];
130

    
131
      break;
132
  }
133

    
134
  // Alter the description for allowed values depending on the widget type.
135
  if ($instance['widget']['type'] == 'options_onoff') {
136
    $form['allowed_values']['#description'] .= '<p>' . t("For a 'single on/off checkbox' widget, define the 'off' value first, then the 'on' value in the <strong>Allowed values</strong> section. Note that the checkbox will be labeled with the label of the 'on' value.") . '</p>';
137
  }
138
  elseif ($instance['widget']['type'] == 'options_buttons') {
139
    $form['allowed_values']['#description'] .= '<p>' . t("The 'checkboxes/radio buttons' widget will display checkboxes if the <em>Number of values</em> option is greater than 1 for this field, otherwise radios will be displayed.") . '</p>';
140
  }
141
  $form['allowed_values']['#description'] .= '<p>' . t('Allowed HTML tags in labels: @tags', array('@tags' => _field_filter_xss_display_allowed_tags())) . '</p>';
142

    
143
  $form['allowed_values_function'] = array(
144
    '#type' => 'value',
145
    '#value' => $settings['allowed_values_function'],
146
  );
147
  $form['allowed_values_function_display'] = array(
148
    '#type' => 'item',
149
    '#title' => t('Allowed values list'),
150
    '#markup' => t('The value of this field is being determined by the %function function and may not be changed.', array('%function' => $settings['allowed_values_function'])),
151
    '#access' => !empty($settings['allowed_values_function']),
152
  );
153

    
154
  return $form;
155
}
156

    
157
/**
158
 * Element validate callback; check that the entered values are valid.
159
 */
160
function list_allowed_values_setting_validate($element, &$form_state) {
161
  $field = $element['#field'];
162
  $has_data = $element['#field_has_data'];
163
  $field_type = $field['type'];
164
  $generate_keys = ($field_type == 'list_integer' || $field_type == 'list_float') && !$has_data;
165

    
166
  $values = list_extract_allowed_values($element['#value'], $field['type'], $generate_keys);
167

    
168
  if (!is_array($values)) {
169
    form_error($element, t('Allowed values list: invalid input.'));
170
  }
171
  else {
172
    // Check that keys are valid for the field type.
173
    foreach ($values as $key => $value) {
174
      if ($field_type == 'list_integer' && !preg_match('/^-?\d+$/', $key)) {
175
        form_error($element, t('Allowed values list: keys must be integers.'));
176
        break;
177
      }
178
      if ($field_type == 'list_float' && !is_numeric($key)) {
179
        form_error($element, t('Allowed values list: each key must be a valid integer or decimal.'));
180
        break;
181
      }
182
      elseif ($field_type == 'list_text' && drupal_strlen($key) > 255) {
183
        form_error($element, t('Allowed values list: each key must be a string at most 255 characters long.'));
184
        break;
185
      }
186
    }
187

    
188
    // Prevent removing values currently in use.
189
    if ($has_data) {
190
      $lost_keys = array_diff(array_keys($field['settings']['allowed_values']), array_keys($values));
191
      if (_list_values_in_use($field, $lost_keys)) {
192
        form_error($element, t('Allowed values list: some values are being removed while currently in use.'));
193
      }
194
    }
195

    
196
    form_set_value($element, $values, $form_state);
197
  }
198
}
199

    
200
/**
201
* Form element #value_callback: assembles the allowed values for 'boolean' fields.
202
*/
203
function list_boolean_allowed_values_callback($element, $input, $form_state) {
204
  $on = drupal_array_get_nested_value($form_state['input'], $element['#on_parents']);
205
  $off = drupal_array_get_nested_value($form_state['input'], $element['#off_parents']);
206
  return array($off, $on);
207
}
208

    
209
/**
210
 * Implements hook_field_update_field().
211
 */
212
function list_field_update_field($field, $prior_field, $has_data) {
213
  drupal_static_reset('list_allowed_values');
214
}
215

    
216
/**
217
 * Returns the array of allowed values for a list field.
218
 *
219
 * The strings are not safe for output. Keys and values of the array should be
220
 * sanitized through field_filter_xss() before being displayed.
221
 *
222
 * @param $field
223
 *   The field definition.
224
 * @param $instance
225
 *   (optional) A field instance array. Defaults to NULL.
226
 * @param $entity_type
227
 *   (optional) The type of entity; e.g. 'node' or 'user'. Defaults to NULL.
228
 * @param $entity
229
 *   (optional) The entity object. Defaults to NULL.
230
 *
231
 * @return
232
 *   The array of allowed values. Keys of the array are the raw stored values
233
 *   (number or text), values of the array are the display labels.
234
 */
235
function list_allowed_values($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
236
  $allowed_values = &drupal_static(__FUNCTION__, array());
237

    
238
  if (!isset($allowed_values[$field['id']])) {
239
    $function = $field['settings']['allowed_values_function'];
240
    // If $cacheable is FALSE, then the allowed values are not statically
241
    // cached. See list_test_dynamic_values_callback() for an example of
242
    // generating dynamic and uncached values.
243
    $cacheable = TRUE;
244
    if (!empty($function) && function_exists($function)) {
245
      $values = $function($field, $instance, $entity_type, $entity, $cacheable);
246
    }
247
    else {
248
      $values = $field['settings']['allowed_values'];
249
    }
250

    
251
    if ($cacheable) {
252
      $allowed_values[$field['id']] = $values;
253
    }
254
    else {
255
      return $values;
256
    }
257
  }
258

    
259
  return $allowed_values[$field['id']];
260
}
261

    
262
/**
263
 * Parses a string of 'allowed values' into an array.
264
 *
265
 * @param $string
266
 *   The list of allowed values in string format described in
267
 *   list_allowed_values_string().
268
 * @param $field_type
269
 *   The field type. Either 'list_number' or 'list_text'.
270
 * @param $generate_keys
271
 *   Boolean value indicating whether to generate keys based on the position of
272
 *   the value if a key is not manually specified, and if the value cannot be
273
 *   used as a key. This should only be TRUE for fields of type 'list_number'.
274
 *
275
 * @return
276
 *   The array of extracted key/value pairs, or NULL if the string is invalid.
277
 *
278
 * @see list_allowed_values_string()
279
 */
280
function list_extract_allowed_values($string, $field_type, $generate_keys) {
281
  $values = array();
282

    
283
  $list = explode("\n", $string);
284
  $list = array_map('trim', $list);
285
  $list = array_filter($list, 'strlen');
286

    
287
  $generated_keys = $explicit_keys = FALSE;
288
  foreach ($list as $position => $text) {
289
    $value = $key = FALSE;
290

    
291
    // Check for an explicit key.
292
    $matches = array();
293
    if (preg_match('/(.*)\|(.*)/', $text, $matches)) {
294
      $key = $matches[1];
295
      $value = $matches[2];
296
      $explicit_keys = TRUE;
297
    }
298
    // Otherwise see if we can use the value as the key. Detecting true integer
299
    // strings takes a little trick.
300
    elseif ($field_type == 'list_text'
301
    || ($field_type == 'list_float' && is_numeric($text))
302
    || ($field_type == 'list_integer' && is_numeric($text) && (float) $text == intval($text))) {
303
      $key = $value = $text;
304
      $explicit_keys = TRUE;
305
    }
306
    // Otherwise see if we can generate a key from the position.
307
    elseif ($generate_keys) {
308
      $key = (string) $position;
309
      $value = $text;
310
      $generated_keys = TRUE;
311
    }
312
    else {
313
      return;
314
    }
315

    
316
    // Float keys are represented as strings and need to be disambiguated
317
    // ('.5' is '0.5').
318
    if ($field_type == 'list_float' && is_numeric($key)) {
319
      $key = (string) (float) $key;
320
    }
321

    
322
    $values[$key] = $value;
323
  }
324

    
325
  // We generate keys only if the list contains no explicit key at all.
326
  if ($explicit_keys && $generated_keys) {
327
    return;
328
  }
329

    
330
  return $values;
331
}
332

    
333
/**
334
 * Generates a string representation of an array of 'allowed values'.
335
 *
336
 * This string format is suitable for edition in a textarea.
337
 *
338
 * @param $values
339
 *   An array of values, where array keys are values and array values are
340
 *   labels.
341
 *
342
 * @return
343
 *   The string representation of the $values array:
344
 *    - Values are separated by a carriage return.
345
 *    - Each value is in the format "value|label" or "value".
346
 */
347
function list_allowed_values_string($values) {
348
  $lines = array();
349
  foreach ($values as $key => $value) {
350
    $lines[] = "$key|$value";
351
  }
352
  return implode("\n", $lines);
353
}
354

    
355
/**
356
 * Implements hook_field_update_forbid().
357
 */
358
function list_field_update_forbid($field, $prior_field, $has_data) {
359
  if ($field['module'] == 'list' && $has_data) {
360
    // Forbid any update that removes allowed values with actual data.
361
    $lost_keys = array_diff(array_keys($prior_field['settings']['allowed_values']), array_keys($field['settings']['allowed_values']));
362
    if (_list_values_in_use($field, $lost_keys)) {
363
      throw new FieldUpdateForbiddenException(t('A list field (@field_name) with existing data cannot have its keys changed.', array('@field_name' => $field['field_name'])));
364
    }
365
  }
366
}
367

    
368
/**
369
 * Checks if a list of values are being used in actual field values.
370
 */
371
function _list_values_in_use($field, $values) {
372
  if ($values) {
373
    $query = new EntityFieldQuery();
374
    $found = $query
375
      ->fieldCondition($field['field_name'], 'value', $values)
376
      ->range(0, 1)
377
      ->execute();
378
    return !empty($found);
379
  }
380

    
381
  return FALSE;
382
}
383

    
384
/**
385
 * Implements hook_field_validate().
386
 *
387
 * Possible error codes:
388
 * - 'list_illegal_value': The value is not part of the list of allowed values.
389
 */
390
function list_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
391
  $allowed_values = list_allowed_values($field, $instance, $entity_type, $entity);
392
  foreach ($items as $delta => $item) {
393
    if (!empty($item['value'])) {
394
      if (!empty($allowed_values) && !isset($allowed_values[$item['value']])) {
395
        $errors[$field['field_name']][$langcode][$delta][] = array(
396
          'error' => 'list_illegal_value',
397
          'message' => t('%name: illegal value.', array('%name' => $instance['label'])),
398
        );
399
      }
400
    }
401
  }
402
}
403

    
404
/**
405
 * Implements hook_field_is_empty().
406
 */
407
function list_field_is_empty($item, $field) {
408
  if (empty($item['value']) && (string) $item['value'] !== '0') {
409
    return TRUE;
410
  }
411
  return FALSE;
412
}
413

    
414
/**
415
 * Implements hook_field_widget_info_alter().
416
 *
417
 * The List module does not implement widgets of its own, but reuses the
418
 * widgets defined in options.module.
419
 *
420
 * @see list_options_list()
421
 */
422
function list_field_widget_info_alter(&$info) {
423
  $widgets = array(
424
    'options_select' => array('list_integer', 'list_float', 'list_text'),
425
    'options_buttons' => array('list_integer', 'list_float', 'list_text', 'list_boolean'),
426
    'options_onoff' => array('list_boolean'),
427
  );
428

    
429
  foreach ($widgets as $widget => $field_types) {
430
    $info[$widget]['field types'] = array_merge($info[$widget]['field types'], $field_types);
431
  }
432
}
433

    
434
/**
435
 * Implements hook_options_list().
436
 */
437
function list_options_list($field, $instance, $entity_type, $entity) {
438
  return list_allowed_values($field, $instance, $entity_type, $entity);
439
}
440

    
441
/**
442
 * Implements hook_field_formatter_info().
443
 */
444
function list_field_formatter_info() {
445
  return array(
446
    'list_default' => array(
447
      'label' => t('Default'),
448
      'field types' => array('list_integer', 'list_float', 'list_text', 'list_boolean'),
449
    ),
450
    'list_key' => array(
451
      'label' => t('Key'),
452
      'field types' => array('list_integer', 'list_float', 'list_text', 'list_boolean'),
453
    ),
454
  );
455
}
456

    
457
/**
458
 * Implements hook_field_formatter_view().
459
 */
460
function list_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
461
  $element = array();
462

    
463
  switch ($display['type']) {
464
    case 'list_default':
465
      $allowed_values = list_allowed_values($field, $instance, $entity_type, $entity);
466
      foreach ($items as $delta => $item) {
467
        if (isset($allowed_values[$item['value']])) {
468
          $output = field_filter_xss($allowed_values[$item['value']]);
469
        }
470
        else {
471
          // If no match was found in allowed values, fall back to the key.
472
          $output = field_filter_xss($item['value']);
473
        }
474
        $element[$delta] = array('#markup' => $output);
475
      }
476
      break;
477

    
478
    case 'list_key':
479
      foreach ($items as $delta => $item) {
480
        $element[$delta] = array('#markup' => field_filter_xss($item['value']));
481
      }
482
      break;
483
  }
484

    
485
  return $element;
486
}