summaryrefslogtreecommitdiff
path: root/modules/field/modules/options/options.module
blob: 22099fd9e9ed241459e916918dd406c4c2cf179d (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
438
439
440
441
442
443
444
445
446
447
<?php
// $Id$

/**
 * @file
 * Defines selection, check box and radio button widgets for text and numeric fields.
 */

/**
 * Implement hook_theme().
 */
function options_theme() {
  return array(
    'options_select' => array(
      'render element' => 'element',
    ),
    'options_buttons' => array(
      'render element' => 'element',
    ),
    'options_onoff' => array(
      'render element' => 'element',
    ),
    'options_none' => array(
      'variables' => array('instance' => NULL),
      ),
  );
}

/**
 * Implement hook_field_widget_info().
 *
 * We need custom handling of multiple values because we need
 * to combine them into a options list rather than display
 * cardinality elements. We will use the field module's default
 * handling for default values.
 *
 * 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 options_field_widget_info() {

  return array(
    'options_select' => array(
      'label' => t('Select list'),
      'field types' => array('list', 'list_boolean', 'list_text', 'list_number'),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
      ),
    ),
    'options_buttons' => array(
      'label' => t('Check boxes/radio buttons'),
      'field types' => array('list', 'list_boolean', 'list_text', 'list_number'),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
      ),
    ),
    'options_onoff' => array(
      'label' => t('Single on/off checkbox'),
      'field types' => array('list_boolean'),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
      ),
    ),
  );
}

/**
 * Implement hook_element_info().
 */
function options_element_info() {
  $types['options_select'] = array(
    '#input' => TRUE,
    '#columns' => array('value'),
    '#delta' => 0,
    '#process' => array('options_select_elements_process'),
  );
  $types['options_buttons'] = array(
    '#input' => TRUE,
    '#columns' => array('value'),
    '#delta' => 0,
    '#process' => array('options_buttons_elements_process'),
  );
  $types['options_onoff'] = array(
    '#input' => TRUE,
    '#columns' => array('value'),
    '#delta' => 0,
    '#process' => array('options_onoff_elements_process'),
  );
  return $types;
}

/**
 * Implement hook_field_widget().
 */
function options_field_widget(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $element += array(
    '#type' => $instance['widget']['type'],
    '#default_value' => !empty($items) ? $items : array(),
  );
  return $element;
}

/**
 * Implement hook_field_widget_error().
 */
function options_field_widget_error($element, $error) {
  $field_key  = $element['#columns'][0];
  form_error($element[$field_key], $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 options_buttons_elements_process($element, &$form_state, $form) {
  $field = $form['#fields'][$element['#field_name']]['field'];
  $instance = $form['#fields'][$element['#field_name']]['instance'];
  $field_key  = $element['#columns'][0];

  // See if this element is in the database format or the transformed format,
  // and transform it if necessary.
  if (is_array($element['#value']) && !array_key_exists($field_key, $element['#value'])) {
    $element['#value'] = options_data2form($element, $element['#default_value'], $field);
  }
  $options = options_options($field, $instance);
  $required = isset($element['#required']) ? $element['#required'] : $instance['required'];
  $multiple = isset($element['#multiple']) ? $element['#multiple'] : $field['cardinality'] > 1 || $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED;

  // Incoming #value is an array (checkboxes) or integer (radios).
  $keys = $element['#value'][$field_key];
  if (!is_array($keys)) {
    $keys = array($keys);
  }

  // Multiple (checkboxes) need #default_value to be an array, and
  // non-multiple (radios) need a single default value. If #value is
  // empty we loop won't run, so initialize $value to the right type.
  $value = $multiple ? array() : '';
  foreach ($keys as $key) {
    if ($multiple) {
      $value[] = $key;
    }
    else {
      $value = $key;
      break;
    }
  }

  // If required and there is one option, make it the default.
  if ($required && count($options) == 1) {
    $keys = array_keys($options);
    if ($multiple) {
      $value = $keys;
    }
    else {
      $value = $keys[0];
    }
  }

  $element[$field_key] = array(
    '#type' => $multiple ? 'checkboxes' : 'radios',
    '#title' => $element['#title'],
    '#description' => $element['#description'],
    '#required' => $required,
    '#multiple' => $multiple,
    '#options' => $options,
    '#default_value' => $value,
  );

  // Set #element_validate in a way that it will not wipe out other
  // validation functions already set by other modules.
  if (empty($element['#element_validate'])) {
    $element['#element_validate'] = array();
  }
  array_unshift($element['#element_validate'], 'options_validate');

  // Make sure field info will be available to the validator which
  // does not get the values in $form.
  $form_state['#fields'][$element['#field_name']] = $form['#fields'][$element['#field_name']];
  return $element;
}

/**
 * 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 options_select_elements_process($element, &$form_state, $form) {
  $field = $form['#fields'][$element['#field_name']]['field'];
  $instance = $form['#fields'][$element['#field_name']]['instance'];
  $field_key  = $element['#columns'][0];

  // See if this element is in the database format or the transformed format,
  // and transform it if necessary.
  if (is_array($element['#value']) && !array_key_exists($field_key, $element['#value'])) {
    $element['#value'] = options_data2form($element, $element['#default_value'], $field);
  }

  $options = options_options($field, $instance);
  $element[$field_key] = array(
    '#type' => 'select',
    '#title' => $element['#title'],
    '#description' => $element['#description'],
    '#required' => isset($element['#required']) ? $element['#required'] : $instance['required'],
    '#multiple' => isset($element['#multiple']) ? $element['#multiple'] : $field['cardinality'] > 1 || $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED,
    '#options' => $options,
    '#default_value' => isset($element['#value'][$field_key]) ? $element['#value'][$field_key] : NULL,
  );

  // Set #element_validate in a way that it will not wipe out other
  // validation functions already set by other modules.
  if (empty($element['#element_validate'])) {
    $element['#element_validate'] = array();
  }
  array_unshift($element['#element_validate'], 'options_validate');

  // Make sure field info will be available to the validator which
  // does not get the values in $form.
  $form_state['#fields'][$element['#field_name']] = $form['#fields'][$element['#field_name']];
  return $element;
}

/**
 * Process an individual element.
 *
 * Build the form element. When creating a form using FAPI #process,
 * note that $element['#value'] is already set.
 */
function options_onoff_elements_process($element, &$form_state, $form) {
  $field = $form['#fields'][$element['#field_name']]['field'];
  $instance = $form['#fields'][$element['#field_name']]['instance'];
  $field_key  = $element['#columns'][0];

  // See if this element is in the database format or the transformed format,
  // and transform it if necessary.
  if (is_array($element['#value']) && !array_key_exists($field_key, $element['#value'])) {
    $element['#value'] = options_data2form($element, $element['#default_value'], $field);
  }
  $options = options_options($field, $instance);
  $keys = array_keys($options);
  $on_value = (!empty($keys) && isset($keys[1])) ? $keys[1] : NULL;
  $element[$field_key] = array(
    '#type' => 'checkbox',
    '#title' => isset($options[$on_value]) ? $options[$on_value] : '',
    '#description' => $element['#description'],
    '#default_value' => isset($element['#value'][$field_key][0]) ? $element['#value'][$field_key][0] == $on_value : FALSE,
    '#return_value' => $on_value,
  );

  // Set #element_validate in a way that it will not wipe out other
  // validation functions already set by other modules.
  if (empty($element['#element_validate'])) {
    $element['#element_validate'] = array();
  }
  array_unshift($element['#element_validate'], 'options_validate');

  // Make sure field info will be available to the validator which
  // does not get the values in $form.
  $form_state['#fields'][$element['#field_name']] = $form['#fields'][$element['#field_name']];
  return $element;
}

/**
 * FAPI function to validate options element.
 */
function options_validate($element, &$form_state) {
  // Transpose selections from field => delta to delta => field,
  // turning cardinality selected options into cardinality parent elements.
  // Immediate parent is the delta, need to get back to parent's parent
  // to create cardinality elements.
  $field = $form_state['#fields'][$element['#field_name']]['field'];
  $items = options_form2data($element, $field);
  form_set_value($element, $items, $form_state);

  // Check we don't exceed the allowed number of values.
  if ($field['cardinality'] >= 2) {
    // Filter out 'none' value (if present, will always be in key 0)
    $field_key = $element['#columns'][0];
    if (isset($items[0][$field_key]) && $items[0][$field_key] === '') {
      unset($items[0]);
    }
    if (count($items) > $field['cardinality']) {
      $field_key  = $element['#columns'][0];
      form_error($element[$field_key], t('%name: this field cannot hold more that @count values.', array('%name' => t($field['widget']['label']), '@count' => $field['cardinality'])));
    }
  }
}

/**
 * Helper function to transpose the values as stored in the database
 * to the format the widget needs. Can be called anywhere this
 * transformation is needed.
 */
function options_data2form($element, $items, $field) {
  $field_key  = $element['#columns'][0];
  $field = field_info_field($element['#field_name']);
  $instance = field_info_instance($element['#object_type'], $element['#field_name'], $element['#bundle']);
  $options = options_options($field, $instance);

  $items_transposed = options_transpose_array_rows_cols($items);
  $values = (isset($items_transposed[$field_key]) && is_array($items_transposed[$field_key])) ? $items_transposed[$field_key] : array();
  $keys = array();
  foreach ($values as $value) {
    $key = array_search($value, array_keys($options));
    if (isset($key)) {
      $keys[] = $value;
    }
  }
  if ($field['cardinality'] || $element['#type'] == 'options_onoff') {
    return array($field_key => $keys);
  }
  else {
    return !empty($keys) ? array($field_key => $value) : array();
  }
}

/**
 * Helper function to transpose the values returned by submitting the widget
 * to the format to be stored in the field. Can be called anywhere this
 * transformation is needed.
 */
function options_form2data($element, $field) {
  $field_key = $element['#columns'][0];
  $field = field_info_field($element['#field_name']);
  $instance = field_info_instance($element['#object_type'], $element['#field_name'], $element['#bundle']);
  $items = (array) $element[$field_key]['#value'];
  $options = options_options($field, $instance);

  $values = array_values($items);

  if ($element['#type'] == 'options_onoff' && ($values[0] === 0)) {
    $keys = array_keys($options);
    $values = array(array_key_exists(0, $keys) ? $keys[0] : NULL);
  }

  if (empty($values)) {
    $values[] = NULL;
  }
  $result = options_transpose_array_rows_cols(array($field_key => $values));
  return $result;
}

/**
 * Manipulate a 2D array to reverse rows and columns.
 *
 * The default data storage for fields is delta first, column names second.
 * This is sometimes inconvenient for field modules, so this function can be
 * used to present the data in an alternate format.
 *
 * @param $array
 *   The array to be transposed. It must be at least two-dimensional, and
 *   the subarrays must all have the same keys or behavior is undefined.
 * @return
 *   The transposed array.
 */
function options_transpose_array_rows_cols($array) {
  $result = array();
  if (is_array($array)) {
    foreach ($array as $key1 => $value1) {
      if (is_array($value1)) {
        foreach ($value1 as $key2 => $value2) {
          if (!isset($result[$key2])) {
            $result[$key2] = array();
          }
          $result[$key2][$key1] = $value2;
        }
      }
    }
  }
  return $result;
}

/**
 * Helper function for finding the allowed values list for a field.
 *
 * See if there is a module hook for the option values.
 * Otherwise, try list_allowed_values() for an options list.
 */
function options_options($field, $instance) {
  $function = $field['module'] . '_allowed_values';
  $options = function_exists($function) ? $function($field) : (array) list_allowed_values($field);
  // Add an empty choice for :
  // - non required radios
  // - non required selects
  if (!$instance['required']) {
    if ((in_array($instance['widget']['type'], array('options_buttons', 'node_reference_buttons', 'user_reference_buttons')) && !$field['cardinality'])
      || (in_array($instance['widget']['type'], array('options_select', 'node_reference_select', 'user_reference_select')))) {
      $options = array('' => theme('options_none', array('instance' => $instance))) + $options;
    }
  }
  return $options;
}

/**
 *  Theme the label for the empty value for options that are not required.
 *  The default theme will display N/A for a radio list and blank for a select.
 */
function theme_options_none($variables) {
  $instance = $variables['instance'];
  switch ($instance['widget']['type']) {
    case 'options_buttons':
    case 'node_reference_buttons':
    case 'user_reference_buttons':
      return t('N/A');
    case 'options_select':
    case 'node_reference_select':
    case 'user_reference_select':
      return t('- None -');
    default :
      return '';
  }
}

/**
 * FAPI themes for options.
 *
 * The select, checkboxes or radios are already rendered by the
 * select, checkboxes, or radios themes and the HTML output
 * lives in $variables['element']['#children']. Override this theme to
 * make custom changes to the output.
 *
 * $variables['element']['#field_name'] contains the field name
 * $variables['element']['#delta] is the position of this element in the group
 */
function theme_options_select($variables) {
  $element = $variables['element'];
  return $element['#children'];
}

function theme_options_onoff($variables) {
  $element = $variables['element'];
  return $element['#children'];
}

function theme_options_buttons($variables) {
  $element = $variables['element'];
  return $element['#children'];
}