select.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. /**
  3. * Elgg select input
  4. * Displays a select input field
  5. *
  6. * @warning Values of FALSE or NULL will match '' (empty string) but not 0.
  7. *
  8. * @package Elgg
  9. * @subpackage Core
  10. *
  11. * @uses $vars['value'] The current value or an array of current values if multiple is true
  12. * @uses $vars['options'] An array of strings representing the options for the dropdown field
  13. * @uses $vars['options_values'] An associative array of "value" => "option"
  14. * where "value" is the name and "option" is
  15. * the value displayed on the button. Replaces
  16. * $vars['options'] when defined.
  17. * @uses $vars['multiple'] If true, multiselect of values will be allowed in the select box
  18. * @uses $vars['class'] Additional CSS class
  19. */
  20. $vars['class'] = (array) elgg_extract('class', $vars, []);
  21. $vars['class'][] = 'elgg-input-dropdown';
  22. $defaults = array(
  23. 'disabled' => false,
  24. 'value' => '',
  25. 'options_values' => array(),
  26. 'options' => array(),
  27. );
  28. $vars = array_merge($defaults, $vars);
  29. $options_values = $vars['options_values'];
  30. unset($vars['options_values']);
  31. $options = $vars['options'];
  32. unset($vars['options']);
  33. $value = is_array($vars['value']) ? $vars['value'] : array($vars['value']);
  34. $value = array_map('strval', $value);
  35. unset($vars['value']);
  36. $vars['multiple'] = !empty($vars['multiple']);
  37. // Add trailing [] to name if multiple is enabled to allow the form to send multiple values
  38. if ($vars['multiple'] && !empty($vars['name']) && is_string($vars['name'])) {
  39. if (substr($vars['name'], -2) != '[]') {
  40. $vars['name'] = $vars['name'] . '[]';
  41. }
  42. }
  43. $options_list = '';
  44. if ($options_values) {
  45. foreach ($options_values as $opt_value => $option) {
  46. $option_attrs = array(
  47. 'value' => $opt_value,
  48. 'selected' => in_array((string)$opt_value, $value),
  49. );
  50. $options_list .= elgg_format_element('option', $option_attrs, $option);
  51. }
  52. } else {
  53. if (is_array($options)) {
  54. foreach ($options as $option) {
  55. $option_attrs = ['selected' => in_array((string)$option, $value)];
  56. $options_list .= elgg_format_element('option', $option_attrs, $option);
  57. }
  58. }
  59. }
  60. echo elgg_format_element('select', $vars, $options_list);