summaryrefslogtreecommitdiff
path: root/modules/field/modules/options/options.module
blob: 74573b4fdd137febc7247cbb55032e42de67dd55 (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
<?php
// $Id$

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

/**
 * Implements hook_theme().
 */
function options_theme() {
  return array(
    'options_none' => array(
      'variables' => array('instance' => NULL),
    ),
  );
}

/**
 * Implements hook_field_widget_info().
 */
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,
      ),
    ),
  );
}

/**
 * Implements hook_field_widget().
 */
function options_field_widget(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  // Abstract over the actual field columns, to allow different field types to
  // reuse those widgets.
  $value_key = key($field['columns']);
  $multiple = $field['cardinality'] > 1 || $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED;
  // Form API 'checkboxes' do not suport 0 as an option, so we replace it with
  // a placeholder within the form workflow.
  $zero_placeholder = $instance['widget']['type'] == 'options_buttons' && $multiple;
  // Collect available options for the field.
  $options = options_get_options($field, $instance, $zero_placeholder);
  // Put current field values in shape.
  $default_value = _options_storage_to_form($items, $options, $value_key, $zero_placeholder);

  switch ($instance['widget']['type']) {
    case 'options_select':
      $element += array(
        '#type' => 'select',
        '#default_value' => $default_value,
        // Do not display a 'multiple' select box if there is only one option.
        '#multiple' => $multiple && count($options) > 1,
        '#options' => $options,
        '#value_key' => $value_key,
        '#element_validate' => array('options_field_widget_validate'),
      );
      break;

    case 'options_buttons':
      $type = $multiple ? 'checkboxes' : 'radios';
      // If required and there is one single option, preselect it.
      if ($element['#required'] && count($options) == 1) {
        $default_value = array(key($options));
      }
      $element += array(
        '#type' => $type,
        // Radio buttons need a scalar value.
        '#default_value' => ($type == 'radios') ? reset($default_value) : $default_value,
        '#options' => $options,
        '#zero_placeholder' => $zero_placeholder,
        '#value_key' => $value_key,
        '#element_validate' => array('options_field_widget_validate'),
      );
      break;

    case 'options_onoff':
      $keys = array_keys($options);
      $off_value = (!empty($keys) && isset($keys[0])) ? $keys[0] : NULL;
      $on_value = (!empty($keys) && isset($keys[1])) ? $keys[1] : NULL;
      $element += array(
        '#type' => 'checkbox',
        '#title' => isset($options[$on_value]) ? $options[$on_value] : '',
        '#default_value' => (isset($default_value[0]) && $default_value[0] == $on_value) ? 1 : 0,
        '#on_value' => $on_value,
        '#off_value' => $off_value,
        '#value_key' => $value_key,
        '#element_validate' => array('options_field_widget_validate'),
      );
      break;
  }

  return $element;
}

/**
 * Form element validation handler for options element.
 */
function options_field_widget_validate($element, &$form_state) {
  $field = $form_state['complete form']['#fields'][$element['#field_name']]['field'];
  $instance = $form_state['complete form']['#fields'][$element['#field_name']]['instance'];

  // Transpose selections from field => delta to delta => field, turning
  // multiple selected options into multiple parent elements.
  $items = _options_form_to_storage($element);
  form_set_value($element, $items, $form_state);

  // Check that we don't exceed the allowed number of values.
  if ($field['cardinality'] >= 2 && $field['cardinality'] != FIELD_CARDINALITY_UNLIMITED) {
    if (count($items) > $field['cardinality']) {
      form_error($element, t('%name: this field cannot hold more than @count values.', array('%name' => t($instance['label']), '@count' => $field['cardinality'])));
    }
  }
}

/**
 * Prepares the options for a field.
 */
function options_get_options($field, $instance, $zero_placeholder) {
  // Check if there is a module hook for the option values, otherwise try
  // list_allowed_values() for an options list.
  // @todo This should be turned into a hook_options_allowed_values(), exposed
  // by options.module.
  $function = $field['module'] . '_allowed_values';
  $options = function_exists($function) ? $function($field) : (array) list_allowed_values($field);

  // Substitute the '_0' placeholder.
  if ($zero_placeholder) {
    $values = array_keys($options);
    // Use a strict comparison, because 0 == 'any string'.
    $index = array_search(0, $values, TRUE);
    if ($index !== FALSE) {
      $values[$index] = '_0';
      $options = array_combine($values, array_values($options));
    }
  }

  // Add an empty choice for
  // - non required radios
  // - non required selects
  if (!$instance['required']) {
    if (($instance['widget']['type'] == 'options_buttons' && ($field['cardinality'] == 1)) || ($instance['widget']['type'] == 'options_select')) {
      $options = array('_none' => theme('options_none', array('instance' => $instance))) + $options;
    }
  }
  return $options;
}

/**
 * Transforms stored field values into the format the widgets need.
 */
function _options_storage_to_form($items, $options, $column, $zero_placeholder) {
  $items_transposed = options_array_transpose($items);
  $values = (isset($items_transposed[$column]) && is_array($items_transposed[$column])) ? $items_transposed[$column] : array();

  // Substitute the '_0' placeholder.
  if ($zero_placeholder) {
    $index = array_search('0', $values);
    if ($index !== FALSE) {
      $values[$index] = '_0';
    }
  }

  // Discard values that are not in the current list of options.
  $values = array_values(array_intersect($values, array_keys($options)));
  return $values;
}

/**
 * Transforms submitted form values into field storage format.
 */
function _options_form_to_storage($element) {
  $values = array_values((array) $element['#value']);

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

  // Substitute the '_0' placeholder.
  if (!empty($element['#zero_placeholder'])) {
    $index = array_search('_0', $values);
    if ($index !== FALSE) {
      $values[$index] = 0;
    }
  }

  // Filter out the 'none' option. Use a strict comparison, because
  // 0 == 'any string'.
  $index = array_search('_none', $values, TRUE);
  if ($index !== FALSE) {
    unset($values[$index]);
  }

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

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

/**
 * Manipulates 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_array_transpose($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;
}

/**
 * Implements hook_field_widget_error().
 */
function options_field_widget_error($element, $error) {
  form_error($element, $error['message']);
}

/**
 *  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':
      return t('N/A');
    case 'options_select':
      return t('- None -');
    default :
      return '';
  }
}