list.module

You are here

Defines list field types that can be used with the Options module.

Functions

Namesort descending Description
list_allowed_values Returns the array of allowed values for a list field.
list_allowed_values_setting_validate Element validate callback; check that the entered values are valid.
list_allowed_values_string Generates a string representation of an array of 'allowed values'.
list_boolean_allowed_values_callback Form element #value_callback: assembles the allowed values for 'boolean' fields.
list_extract_allowed_values Parses a string of 'allowed values' into an array.
list_field_formatter_info Implements hook_field_formatter_info().
list_field_formatter_view Implements hook_field_formatter_view().
list_field_info Implements hook_field_info().
list_field_is_empty Implements hook_field_is_empty().
list_field_settings_form Implements hook_field_settings_form().
list_field_update_field Implements hook_field_update_field().
list_field_update_forbid Implements hook_field_update_forbid().
list_field_validate Implements hook_field_validate().
list_field_widget_info_alter Implements hook_field_widget_info_alter().
list_help Implements hook_help().
list_options_list Implements hook_options_list().
_list_values_in_use Checks if a list of values are being used in actual field values.

File

modules/field/modules/list/list.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * Defines list field types that can be used with the Options module.
  5. */
  6. /**
  7. * Implements hook_help().
  8. */
  9. function list_help($path, $arg) {
  10. switch ($path) {
  11. case 'admin/help#list':
  12. $output = '';
  13. $output .= '<h3>' . t('About') . '</h3>';
  14. $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>';
  15. return $output;
  16. }
  17. }
  18. /**
  19. * Implements hook_field_info().
  20. */
  21. function list_field_info() {
  22. return array(
  23. 'list_integer' => array(
  24. 'label' => t('List (integer)'),
  25. '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."),
  26. 'settings' => array('allowed_values' => array(), 'allowed_values_function' => ''),
  27. 'default_widget' => 'options_select',
  28. 'default_formatter' => 'list_default',
  29. ),
  30. 'list_float' => array(
  31. 'label' => t('List (float)'),
  32. '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."),
  33. 'settings' => array('allowed_values' => array(), 'allowed_values_function' => ''),
  34. 'default_widget' => 'options_select',
  35. 'default_formatter' => 'list_default',
  36. ),
  37. 'list_text' => array(
  38. 'label' => t('List (text)'),
  39. '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."),
  40. 'settings' => array('allowed_values' => array(), 'allowed_values_function' => ''),
  41. 'default_widget' => 'options_select',
  42. 'default_formatter' => 'list_default',
  43. ),
  44. 'list_boolean' => array(
  45. 'label' => t('Boolean'),
  46. 'description' => t('This field stores simple on/off or yes/no options.'),
  47. 'settings' => array('allowed_values' => array(), 'allowed_values_function' => ''),
  48. 'default_widget' => 'options_buttons',
  49. 'default_formatter' => 'list_default',
  50. ),
  51. );
  52. }
  53. /**
  54. * Implements hook_field_settings_form().
  55. */
  56. function list_field_settings_form($field, $instance, $has_data) {
  57. $settings = $field['settings'];
  58. switch ($field['type']) {
  59. case 'list_integer':
  60. case 'list_float':
  61. case 'list_text':
  62. $form['allowed_values'] = array(
  63. '#type' => 'textarea',
  64. '#title' => t('Allowed values list'),
  65. '#default_value' => list_allowed_values_string($settings['allowed_values']),
  66. '#rows' => 10,
  67. '#element_validate' => array('list_allowed_values_setting_validate'),
  68. '#field_has_data' => $has_data,
  69. '#field' => $field,
  70. '#field_type' => $field['type'],
  71. '#access' => empty($settings['allowed_values_function']),
  72. );
  73. $description = '<p>' . t('The possible values this field can contain. Enter one value per line, in the format key|label.');
  74. if ($field['type'] == 'list_integer' || $field['type'] == 'list_float') {
  75. $description .= '<br/>' . t('The key is the stored value, and must be numeric. The label will be used in displayed values and edit forms.');
  76. $description .= '<br/>' . t('The label is optional: if a line contains a single number, it will be used as key and label.');
  77. $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.');
  78. }
  79. else {
  80. $description .= '<br/>' . t('The key is the stored value. The label will be used in displayed values and edit forms.');
  81. $description .= '<br/>' . t('The label is optional: if a line contains a single string, it will be used as key and label.');
  82. }
  83. $description .= '</p>';
  84. $form['allowed_values']['#description'] = $description;
  85. break;
  86. case 'list_boolean':
  87. $values = $settings['allowed_values'];
  88. $off_value = array_shift($values);
  89. $on_value = array_shift($values);
  90. $form['allowed_values'] = array(
  91. '#type' => 'value',
  92. '#description' => '',
  93. '#value_callback' => 'list_boolean_allowed_values_callback',
  94. '#access' => empty($settings['allowed_values_function']),
  95. );
  96. $form['allowed_values']['on'] = array(
  97. '#type' => 'textfield',
  98. '#title' => t('On value'),
  99. '#default_value' => $on_value,
  100. '#required' => FALSE,
  101. '#description' => t('If left empty, "1" will be used.'),
  102. // Change #parents to make sure the element is not saved into field
  103. // settings.
  104. '#parents' => array('on'),
  105. );
  106. $form['allowed_values']['off'] = array(
  107. '#type' => 'textfield',
  108. '#title' => t('Off value'),
  109. '#default_value' => $off_value,
  110. '#required' => FALSE,
  111. '#description' => t('If left empty, "0" will be used.'),
  112. // Change #parents to make sure the element is not saved into field
  113. // settings.
  114. '#parents' => array('off'),
  115. );
  116. // Link the allowed value to the on / off elements to prepare for the rare
  117. // case of an alter changing #parents.
  118. $form['allowed_values']['#on_parents'] = &$form['allowed_values']['on']['#parents'];
  119. $form['allowed_values']['#off_parents'] = &$form['allowed_values']['off']['#parents'];
  120. break;
  121. }
  122. // Alter the description for allowed values depending on the widget type.
  123. if ($instance['widget']['type'] == 'options_onoff') {
  124. $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>';
  125. }
  126. elseif ($instance['widget']['type'] == 'options_buttons') {
  127. $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>';
  128. }
  129. $form['allowed_values']['#description'] .= '<p>' . t('Allowed HTML tags in labels: @tags', array('@tags' => _field_filter_xss_display_allowed_tags())) . '</p>';
  130. $form['allowed_values_function'] = array(
  131. '#type' => 'value',
  132. '#value' => $settings['allowed_values_function'],
  133. );
  134. $form['allowed_values_function_display'] = array(
  135. '#type' => 'item',
  136. '#title' => t('Allowed values list'),
  137. '#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'])),
  138. '#access' => !empty($settings['allowed_values_function']),
  139. );
  140. return $form;
  141. }
  142. /**
  143. * Element validate callback; check that the entered values are valid.
  144. */
  145. function list_allowed_values_setting_validate($element, &$form_state) {
  146. $field = $element['#field'];
  147. $has_data = $element['#field_has_data'];
  148. $field_type = $field['type'];
  149. $generate_keys = ($field_type == 'list_integer' || $field_type == 'list_float') && !$has_data;
  150. $values = list_extract_allowed_values($element['#value'], $field['type'], $generate_keys);
  151. if (!is_array($values)) {
  152. form_error($element, t('Allowed values list: invalid input.'));
  153. }
  154. else {
  155. // Check that keys are valid for the field type.
  156. foreach ($values as $key => $value) {
  157. if ($field_type == 'list_integer' && !preg_match('/^-?\d+$/', $key)) {
  158. form_error($element, t('Allowed values list: keys must be integers.'));
  159. break;
  160. }
  161. if ($field_type == 'list_float' && !is_numeric($key)) {
  162. form_error($element, t('Allowed values list: each key must be a valid integer or decimal.'));
  163. break;
  164. }
  165. elseif ($field_type == 'list_text' && drupal_strlen($key) > 255) {
  166. form_error($element, t('Allowed values list: each key must be a string at most 255 characters long.'));
  167. break;
  168. }
  169. }
  170. // Prevent removing values currently in use.
  171. if ($has_data) {
  172. $lost_keys = array_diff(array_keys($field['settings']['allowed_values']), array_keys($values));
  173. if (_list_values_in_use($field, $lost_keys)) {
  174. form_error($element, t('Allowed values list: some values are being removed while currently in use.'));
  175. }
  176. }
  177. form_set_value($element, $values, $form_state);
  178. }
  179. }
  180. /**
  181. * Form element #value_callback: assembles the allowed values for 'boolean' fields.
  182. */
  183. function list_boolean_allowed_values_callback($element, $input, $form_state) {
  184. $on = drupal_array_get_nested_value($form_state['input'], $element['#on_parents']);
  185. $off = drupal_array_get_nested_value($form_state['input'], $element['#off_parents']);
  186. return array($off, $on);
  187. }
  188. /**
  189. * Implements hook_field_update_field().
  190. */
  191. function list_field_update_field($field, $prior_field, $has_data) {
  192. drupal_static_reset('list_allowed_values');
  193. }
  194. /**
  195. * Returns the array of allowed values for a list field.
  196. *
  197. * The strings are not safe for output. Keys and values of the array should be
  198. * sanitized through field_filter_xss() before being displayed.
  199. *
  200. * @param $field
  201. * The field definition.
  202. * @param $instance
  203. * (optional) A field instance array. Defaults to NULL.
  204. * @param $entity_type
  205. * (optional) The type of entity; e.g. 'node' or 'user'. Defaults to NULL.
  206. * @param $entity
  207. * (optional) The entity object. Defaults to NULL.
  208. *
  209. * @return
  210. * The array of allowed values. Keys of the array are the raw stored values
  211. * (number or text), values of the array are the display labels.
  212. */
  213. function list_allowed_values($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
  214. $allowed_values = &drupal_static(__FUNCTION__, array());
  215. if (!isset($allowed_values[$field['id']])) {
  216. $function = $field['settings']['allowed_values_function'];
  217. // If $cacheable is FALSE, then the allowed values are not statically
  218. // cached. See list_test_dynamic_values_callback() for an example of
  219. // generating dynamic and uncached values.
  220. $cacheable = TRUE;
  221. if (!empty($function) && function_exists($function)) {
  222. $values = $function($field, $instance, $entity_type, $entity, $cacheable);
  223. }
  224. else {
  225. $values = $field['settings']['allowed_values'];
  226. }
  227. if ($cacheable) {
  228. $allowed_values[$field['id']] = $values;
  229. }
  230. else {
  231. return $values;
  232. }
  233. }
  234. return $allowed_values[$field['id']];
  235. }
  236. /**
  237. * Parses a string of 'allowed values' into an array.
  238. *
  239. * @param $string
  240. * The list of allowed values in string format described in
  241. * list_allowed_values_string().
  242. * @param $field_type
  243. * The field type. Either 'list_number' or 'list_text'.
  244. * @param $generate_keys
  245. * Boolean value indicating whether to generate keys based on the position of
  246. * the value if a key is not manually specified, and if the value cannot be
  247. * used as a key. This should only be TRUE for fields of type 'list_number'.
  248. *
  249. * @return
  250. * The array of extracted key/value pairs, or NULL if the string is invalid.
  251. *
  252. * @see list_allowed_values_string()
  253. */
  254. function list_extract_allowed_values($string, $field_type, $generate_keys) {
  255. $values = array();
  256. $list = explode("\n", $string);
  257. $list = array_map('trim', $list);
  258. $list = array_filter($list, 'strlen');
  259. $generated_keys = $explicit_keys = FALSE;
  260. foreach ($list as $position => $text) {
  261. $value = $key = FALSE;
  262. // Check for an explicit key.
  263. $matches = array();
  264. if (preg_match('/(.*)\|(.*)/', $text, $matches)) {
  265. $key = $matches[1];
  266. $value = $matches[2];
  267. $explicit_keys = TRUE;
  268. }
  269. // Otherwise see if we can use the value as the key. Detecting true integer
  270. // strings takes a little trick.
  271. elseif ($field_type == 'list_text'
  272. || ($field_type == 'list_float' && is_numeric($text))
  273. || ($field_type == 'list_integer' && is_numeric($text) && (float) $text == intval($text))) {
  274. $key = $value = $text;
  275. $explicit_keys = TRUE;
  276. }
  277. // Otherwise see if we can generate a key from the position.
  278. elseif ($generate_keys) {
  279. $key = (string) $position;
  280. $value = $text;
  281. $generated_keys = TRUE;
  282. }
  283. else {
  284. return;
  285. }
  286. // Float keys are represented as strings and need to be disambiguated
  287. // ('.5' is '0.5').
  288. if ($field_type == 'list_float' && is_numeric($key)) {
  289. $key = (string) (float) $key;
  290. }
  291. $values[$key] = $value;
  292. }
  293. // We generate keys only if the list contains no explicit key at all.
  294. if ($explicit_keys && $generated_keys) {
  295. return;
  296. }
  297. return $values;
  298. }
  299. /**
  300. * Generates a string representation of an array of 'allowed values'.
  301. *
  302. * This string format is suitable for edition in a textarea.
  303. *
  304. * @param $values
  305. * An array of values, where array keys are values and array values are
  306. * labels.
  307. *
  308. * @return
  309. * The string representation of the $values array:
  310. * - Values are separated by a carriage return.
  311. * - Each value is in the format "value|label" or "value".
  312. */
  313. function list_allowed_values_string($values) {
  314. $lines = array();
  315. foreach ($values as $key => $value) {
  316. $lines[] = "$key|$value";
  317. }
  318. return implode("\n", $lines);
  319. }
  320. /**
  321. * Implements hook_field_update_forbid().
  322. */
  323. function list_field_update_forbid($field, $prior_field, $has_data) {
  324. if ($field['module'] == 'list' && $has_data) {
  325. // Forbid any update that removes allowed values with actual data.
  326. $lost_keys = array_diff(array_keys($prior_field['settings']['allowed_values']), array_keys($field['settings']['allowed_values']));
  327. if (_list_values_in_use($field, $lost_keys)) {
  328. throw new FieldUpdateForbiddenException(t('A list field (@field_name) with existing data cannot have its keys changed.', array('@field_name' => $field['field_name'])));
  329. }
  330. }
  331. }
  332. /**
  333. * Checks if a list of values are being used in actual field values.
  334. */
  335. function _list_values_in_use($field, $values) {
  336. if ($values) {
  337. $query = new EntityFieldQuery();
  338. $found = $query
  339. ->fieldCondition($field['field_name'], 'value', $values)
  340. ->range(0, 1)
  341. ->execute();
  342. return !empty($found);
  343. }
  344. return FALSE;
  345. }
  346. /**
  347. * Implements hook_field_validate().
  348. *
  349. * Possible error codes:
  350. * - 'list_illegal_value': The value is not part of the list of allowed values.
  351. */
  352. function list_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  353. $allowed_values = list_allowed_values($field, $instance, $entity_type, $entity);
  354. foreach ($items as $delta => $item) {
  355. if (!empty($item['value'])) {
  356. if (!empty($allowed_values) && !isset($allowed_values[$item['value']])) {
  357. $errors[$field['field_name']][$langcode][$delta][] = array(
  358. 'error' => 'list_illegal_value',
  359. 'message' => t('%name: illegal value.', array('%name' => $instance['label'])),
  360. );
  361. }
  362. }
  363. }
  364. }
  365. /**
  366. * Implements hook_field_is_empty().
  367. */
  368. function list_field_is_empty($item, $field) {
  369. if (empty($item['value']) && (string) $item['value'] !== '0') {
  370. return TRUE;
  371. }
  372. return FALSE;
  373. }
  374. /**
  375. * Implements hook_field_widget_info_alter().
  376. *
  377. * The List module does not implement widgets of its own, but reuses the
  378. * widgets defined in options.module.
  379. *
  380. * @see list_options_list()
  381. */
  382. function list_field_widget_info_alter(&$info) {
  383. $widgets = array(
  384. 'options_select' => array('list_integer', 'list_float', 'list_text'),
  385. 'options_buttons' => array('list_integer', 'list_float', 'list_text', 'list_boolean'),
  386. 'options_onoff' => array('list_boolean'),
  387. );
  388. foreach ($widgets as $widget => $field_types) {
  389. $info[$widget]['field types'] = array_merge($info[$widget]['field types'], $field_types);
  390. }
  391. }
  392. /**
  393. * Implements hook_options_list().
  394. */
  395. function list_options_list($field, $instance, $entity_type, $entity) {
  396. return list_allowed_values($field, $instance, $entity_type, $entity);
  397. }
  398. /**
  399. * Implements hook_field_formatter_info().
  400. */
  401. function list_field_formatter_info() {
  402. return array(
  403. 'list_default' => array(
  404. 'label' => t('Default'),
  405. 'field types' => array('list_integer', 'list_float', 'list_text', 'list_boolean'),
  406. ),
  407. 'list_key' => array(
  408. 'label' => t('Key'),
  409. 'field types' => array('list_integer', 'list_float', 'list_text', 'list_boolean'),
  410. ),
  411. );
  412. }
  413. /**
  414. * Implements hook_field_formatter_view().
  415. */
  416. function list_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  417. $element = array();
  418. switch ($display['type']) {
  419. case 'list_default':
  420. $allowed_values = list_allowed_values($field, $instance, $entity_type, $entity);
  421. foreach ($items as $delta => $item) {
  422. if (isset($allowed_values[$item['value']])) {
  423. $output = field_filter_xss($allowed_values[$item['value']]);
  424. }
  425. else {
  426. // If no match was found in allowed values, fall back to the key.
  427. $output = field_filter_xss($item['value']);
  428. }
  429. $element[$delta] = array('#markup' => $output);
  430. }
  431. break;
  432. case 'list_key':
  433. foreach ($items as $delta => $item) {
  434. $element[$delta] = array('#markup' => field_filter_xss($item['value']));
  435. }
  436. break;
  437. }
  438. return $element;
  439. }