Projet

Général

Profil

Paste
Télécharger (11,8 ko) Statistiques
| Branche: | Révision:

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

1
<?php
2

    
3
/**
4
 * @file
5
 * Defines selection, check box and radio button widgets for text and numeric fields.
6
 */
7

    
8
/**
9
 * Implements hook_help().
10
 */
11
function options_help($path, $arg) {
12
  switch ($path) {
13
    case 'admin/help#options':
14
      $output = '';
15
      $output .= '<h3>' . t('About') . '</h3>';
16
      $output .= '<p>' . t('The Options module defines checkbox, selection, and other input widgets for the Field module. 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_theme().
23
 */
24
function options_theme() {
25
  return array(
26
    'options_none' => array(
27
      'variables' => array('instance' => NULL, 'option' => NULL),
28
    ),
29
  );
30
}
31

    
32
/**
33
 * Implements hook_field_widget_info().
34
 *
35
 * Field type modules willing to use those widgets should:
36
 * - Use hook_field_widget_info_alter() to append their field own types to the
37
 *   list of types supported by the widgets,
38
 * - Implement hook_options_list() to provide the list of options.
39
 * See list.module.
40
 */
41
function options_field_widget_info() {
42
  return array(
43
    'options_select' => array(
44
      'label' => t('Select list'),
45
      'field types' => array(),
46
      'behaviors' => array(
47
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
48
      ),
49
    ),
50
    'options_buttons' => array(
51
      'label' => t('Check boxes/radio buttons'),
52
      'field types' => array(),
53
      'behaviors' => array(
54
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
55
      ),
56
    ),
57
    'options_onoff' => array(
58
      'label' => t('Single on/off checkbox'),
59
      'field types' => array(),
60
      'behaviors' => array(
61
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
62
      ),
63
      'settings' => array('display_label' => 0),
64
    ),
65
  );
66
}
67

    
68
/**
69
 * Implements hook_field_widget_form().
70
 */
71
function options_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
72
  // Abstract over the actual field columns, to allow different field types to
73
  // reuse those widgets.
74
  $value_key = key($field['columns']);
75

    
76
  $type = str_replace('options_', '', $instance['widget']['type']);
77
  $multiple = $field['cardinality'] > 1 || $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED;
78
  $required = $element['#required'];
79
  $has_value = isset($items[0][$value_key]);
80
  $properties = _options_properties($type, $multiple, $required, $has_value);
81

    
82
  $entity_type = $element['#entity_type'];
83
  $entity = $element['#entity'];
84

    
85
  // Prepare the list of options.
86
  $options = _options_get_options($field, $instance, $properties, $entity_type, $entity);
87

    
88
  // Put current field values in shape.
89
  $default_value = _options_storage_to_form($items, $options, $value_key, $properties);
90

    
91
  switch ($type) {
92
    case 'select':
93
      $element += array(
94
        '#type' => 'select',
95
        '#default_value' => $default_value,
96
        // Do not display a 'multiple' select box if there is only one option.
97
        '#multiple' => $multiple && count($options) > 1,
98
        '#options' => $options,
99
      );
100
      break;
101

    
102
    case 'buttons':
103
      // If required and there is one single option, preselect it.
104
      if ($required && count($options) == 1) {
105
        reset($options);
106
        $default_value = array(key($options));
107
      }
108

    
109
      // If this is a single-value field, take the first default value, or
110
      // default to NULL so that the form element is properly recognized as
111
      // not having a default value.
112
      if (!$multiple) {
113
        $default_value = $default_value ? reset($default_value) : NULL;
114
      }
115

    
116
      $element += array(
117
        '#type' => $multiple ? 'checkboxes' : 'radios',
118
        // Radio buttons need a scalar value.
119
        '#default_value' => $default_value,
120
        '#options' => $options,
121
      );
122
      break;
123

    
124
    case 'onoff':
125
      $keys = array_keys($options);
126
      $off_value = array_shift($keys);
127
      $on_value = array_shift($keys);
128
      $element += array(
129
        '#type' => 'checkbox',
130
        '#default_value' => (isset($default_value[0]) && $default_value[0] == $on_value) ? 1 : 0,
131
        '#on_value' => $on_value,
132
        '#off_value' => $off_value,
133
      );
134
      // Override the title from the incoming $element.
135
      $element['#title'] = isset($options[$on_value]) ? $options[$on_value] : '';
136

    
137
      if ($instance['widget']['settings']['display_label']) {
138
        $element['#title'] = $instance['label'];
139
      }
140
      break;
141
  }
142

    
143
  $element += array(
144
    '#value_key' => $value_key,
145
    '#element_validate' => array('options_field_widget_validate'),
146
    '#properties' => $properties,
147
  );
148

    
149
  return $element;
150
}
151

    
152
/**
153
 * Implements hook_field_widget_settings_form().
154
 */
155
function options_field_widget_settings_form($field, $instance) {
156
  $form = array();
157
  if ($instance['widget']['type'] == 'options_onoff') {
158
    $form['display_label'] = array(
159
      '#type' => 'checkbox',
160
      '#title' => t('Use field label instead of the "On value" as label'),
161
      '#default_value' => $instance['widget']['settings']['display_label'],
162
      '#weight' => -1,
163
    );
164
  }
165
  return $form;
166
}
167

    
168
/**
169
 * Form element validation handler for options element.
170
 */
171
function options_field_widget_validate($element, &$form_state) {
172
  if ($element['#required'] && $element['#value'] == '_none') {
173
    form_error($element, t('!name field is required.', array('!name' => $element['#title'])));
174
  }
175
  // Transpose selections from field => delta to delta => field, turning
176
  // multiple selected options into multiple parent elements.
177
  $items = _options_form_to_storage($element);
178
  form_set_value($element, $items, $form_state);
179
}
180

    
181
/**
182
 * Describes the preparation steps required by each widget.
183
 */
184
function _options_properties($type, $multiple, $required, $has_value) {
185
  $base = array(
186
    'filter_xss' => FALSE,
187
    'strip_tags' => FALSE,
188
    'empty_option' => FALSE,
189
    'optgroups' => FALSE,
190
  );
191

    
192
  $properties = array();
193

    
194
  switch ($type) {
195
    case 'select':
196
      $properties = array(
197
        // Select boxes do not support any HTML tag.
198
        'strip_tags' => TRUE,
199
        'optgroups' => TRUE,
200
      );
201
      if ($multiple) {
202
        // Multiple select: add a 'none' option for non-required fields.
203
        if (!$required) {
204
          $properties['empty_option'] = 'option_none';
205
        }
206
      }
207
      else {
208
        // Single select: add a 'none' option for non-required fields,
209
        // and a 'select a value' option for required fields that do not come
210
        // with a value selected.
211
        if (!$required) {
212
          $properties['empty_option'] = 'option_none';
213
        }
214
        elseif (!$has_value) {
215
          $properties['empty_option'] = 'option_select';
216
        }
217
      }
218
      break;
219

    
220
    case 'buttons':
221
      $properties = array(
222
        'filter_xss' => TRUE,
223
      );
224
      // Add a 'none' option for non-required radio buttons.
225
      if (!$required && !$multiple) {
226
        $properties['empty_option'] = 'option_none';
227
      }
228
      break;
229

    
230
    case 'onoff':
231
      $properties = array(
232
        'filter_xss' => TRUE,
233
      );
234
      break;
235
  }
236

    
237
  return $properties + $base;
238
}
239

    
240
/**
241
 * Collects the options for a field.
242
 */
243
function _options_get_options($field, $instance, $properties, $entity_type, $entity) {
244
  // Get the list of options.
245
  $options = (array) module_invoke($field['module'], 'options_list', $field, $instance, $entity_type, $entity);
246

    
247
  // Sanitize the options.
248
  _options_prepare_options($options, $properties);
249

    
250
  if (!$properties['optgroups']) {
251
    $options = options_array_flatten($options);
252
  }
253

    
254
  if ($properties['empty_option']) {
255
    $label = theme('options_none', array('instance' => $instance, 'option' => $properties['empty_option']));
256
    $options = array('_none' => $label) + $options;
257
  }
258

    
259
  return $options;
260
}
261

    
262
/**
263
 * Sanitizes the options.
264
 *
265
 * The function is recursive to support optgroups.
266
 */
267
function _options_prepare_options(&$options, $properties) {
268
  foreach ($options as $value => $label) {
269
    // Recurse for optgroups.
270
    if (is_array($label)) {
271
      _options_prepare_options($options[$value], $properties);
272
    }
273
    else {
274
      if ($properties['strip_tags']) {
275
        $options[$value] = strip_tags($label);
276
      }
277
      if ($properties['filter_xss']) {
278
        $options[$value] = field_filter_xss($label);
279
      }
280
    }
281
  }
282
}
283

    
284
/**
285
 * Transforms stored field values into the format the widgets need.
286
 */
287
function _options_storage_to_form($items, $options, $column, $properties) {
288
  $items_transposed = options_array_transpose($items);
289
  $values = (isset($items_transposed[$column]) && is_array($items_transposed[$column])) ? $items_transposed[$column] : array();
290

    
291
  // Discard values that are not in the current list of options. Flatten the
292
  // array if needed.
293
  if ($properties['optgroups']) {
294
    $options = options_array_flatten($options);
295
  }
296
  $values = array_values(array_intersect($values, array_keys($options)));
297
  return $values;
298
}
299

    
300
/**
301
 * Transforms submitted form values into field storage format.
302
 */
303
function _options_form_to_storage($element) {
304
  $values = array_values((array) $element['#value']);
305
  $properties = $element['#properties'];
306

    
307
  // On/off checkbox: transform '0 / 1' into the 'on / off' values.
308
  if ($element['#type'] == 'checkbox') {
309
    $values = array($values[0] ? $element['#on_value'] : $element['#off_value']);
310
  }
311

    
312
  // Filter out the 'none' option. Use a strict comparison, because
313
  // 0 == 'any string'.
314
  if ($properties['empty_option']) {
315
    $index = array_search('_none', $values, TRUE);
316
    if ($index !== FALSE) {
317
      unset($values[$index]);
318
    }
319
  }
320

    
321
  // Make sure we populate at least an empty value.
322
  if (empty($values)) {
323
    $values = array(NULL);
324
  }
325

    
326
  $result = options_array_transpose(array($element['#value_key'] => $values));
327
  return $result;
328
}
329

    
330
/**
331
 * Manipulates a 2D array to reverse rows and columns.
332
 *
333
 * The default data storage for fields is delta first, column names second.
334
 * This is sometimes inconvenient for field modules, so this function can be
335
 * used to present the data in an alternate format.
336
 *
337
 * @param $array
338
 *   The array to be transposed. It must be at least two-dimensional, and
339
 *   the subarrays must all have the same keys or behavior is undefined.
340
 * @return
341
 *   The transposed array.
342
 */
343
function options_array_transpose($array) {
344
  $result = array();
345
  if (is_array($array)) {
346
    foreach ($array as $key1 => $value1) {
347
      if (is_array($value1)) {
348
        foreach ($value1 as $key2 => $value2) {
349
          if (!isset($result[$key2])) {
350
            $result[$key2] = array();
351
          }
352
          $result[$key2][$key1] = $value2;
353
        }
354
      }
355
    }
356
  }
357
  return $result;
358
}
359

    
360
/**
361
 * Flattens an array of allowed values.
362
 *
363
 * @param $array
364
 *   A single or multidimensional array.
365
 * @return
366
 *   A flattened array.
367
 */
368
function options_array_flatten($array) {
369
  $result = array();
370
  if (is_array($array)) {
371
    foreach ($array as $key => $value) {
372
      if (is_array($value)) {
373
        $result += options_array_flatten($value);
374
      }
375
      else {
376
        $result[$key] = $value;
377
      }
378
    }
379
  }
380
  return $result;
381
}
382

    
383
/**
384
 * Implements hook_field_widget_error().
385
 */
386
function options_field_widget_error($element, $error, $form, &$form_state) {
387
  form_error($element, $error['message']);
388
}
389

    
390
/**
391
 * Returns HTML for the label for the empty value for options that are not required.
392
 *
393
 * The default theme will display N/A for a radio list and '- None -' for a select.
394
 *
395
 * @param $variables
396
 *   An associative array containing:
397
 *   - instance: An array representing the widget requesting the options.
398
 *
399
 * @ingroup themeable
400
 */
401
function theme_options_none($variables) {
402
  $instance = $variables['instance'];
403
  $option = $variables['option'];
404

    
405
  $output = '';
406
  switch ($instance['widget']['type']) {
407
    case 'options_buttons':
408
      $output = t('N/A');
409
      break;
410

    
411
    case 'options_select':
412
      $output = ($option == 'option_none' ? t('- None -') : t('- Select a value -'));
413
      break;
414
  }
415

    
416
  return $output;
417
}