SelectBox.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\View\Widget;
  16. use Cake\View\Form\ContextInterface;
  17. use Cake\View\Widget\WidgetInterface;
  18. use Traversable;
  19. /**
  20. * Input widget class for generating a selectbox.
  21. *
  22. * This class is intended as an internal implementation detail
  23. * of Cake\View\Helper\FormHelper and is not intended for direct use.
  24. */
  25. class SelectBox implements WidgetInterface {
  26. /**
  27. * Template instance.
  28. *
  29. * @var \Cake\View\StringTemplate
  30. */
  31. protected $_templates;
  32. /**
  33. * Constructor
  34. *
  35. * @param \Cake\View\StringTemplate $templates Templates list.
  36. */
  37. public function __construct($templates) {
  38. $this->_templates = $templates;
  39. }
  40. /**
  41. * Render a select box form input.
  42. *
  43. * Render a select box input given a set of data. Supported keys
  44. * are:
  45. *
  46. * - `name` - Set the input name.
  47. * - `options` - An array of options.
  48. * - `disabled` - Either true or an array of options to disable.
  49. * When true, the select element will be disabled.
  50. * - `val` - Either a string or an array of options to mark as selected.
  51. * - `empty` - Set to true to add an empty option at the top of the
  52. * option elements. Set to a string to define the display value of the
  53. * empty option.
  54. * - `escape` - Set to false to disable HTML escaping.
  55. *
  56. * ### Options format
  57. *
  58. * The options option can take a variety of data format depending on
  59. * the complexity of HTML you want generated.
  60. *
  61. * You can generate simple options using a basic associative array:
  62. *
  63. * {{{
  64. * 'options' => ['elk' => 'Elk', 'beaver' => 'Beaver']
  65. * }}}
  66. *
  67. * If you need to define additional attributes on your option elements
  68. * you can use the complex form for options:
  69. *
  70. * {{{
  71. * 'options' => [
  72. * ['value' => 'elk', 'text' => 'Elk', 'data-foo' => 'bar'],
  73. * ]
  74. * }}}
  75. *
  76. * This form **requires** that both the `value` and `text` keys be defined.
  77. * If either is not set options will not be generated correctly.
  78. *
  79. * If you need to define option groups you can do those using nested arrays:
  80. *
  81. * {{{
  82. * 'options' => [
  83. * 'Mammals' => [
  84. * 'elk' => 'Elk',
  85. * 'beaver' => 'Beaver'
  86. * ]
  87. * ]
  88. * }}}
  89. *
  90. * And finally, if you need to put attributes on your optgroup elements you
  91. * can do that with a more complex nested array form:
  92. *
  93. * {{{
  94. * 'options' => [
  95. * [
  96. * 'text' => 'Mammals',
  97. * 'data-id' => 1,
  98. * 'options' => [
  99. * 'elk' => 'Elk',
  100. * 'beaver' => 'Beaver'
  101. * ]
  102. * ],
  103. * ]
  104. * }}}
  105. *
  106. * You are free to mix each of the forms in the same option set, and
  107. * nest complex types as required.
  108. *
  109. * @param array $data Data to render with.
  110. * @param \Cake\View\Form\ContextInterface $context The current form context.
  111. * @return string A generated select box.
  112. * @throws \RuntimeException when the name attribute is empty.
  113. */
  114. public function render(array $data, ContextInterface $context) {
  115. $data += [
  116. 'name' => '',
  117. 'empty' => false,
  118. 'escape' => true,
  119. 'options' => [],
  120. 'disabled' => null,
  121. 'val' => null,
  122. ];
  123. if (empty($data['name'])) {
  124. throw new \RuntimeException('Cannot make inputs with empty name attributes.');
  125. }
  126. $options = $this->_renderContent($data);
  127. $name = $data['name'];
  128. unset($data['name'], $data['options'], $data['empty'], $data['val'], $data['escape']);
  129. if (isset($data['disabled']) && is_array($data['disabled'])) {
  130. unset($data['disabled']);
  131. }
  132. $template = 'select';
  133. if (!empty($data['multiple'])) {
  134. $template = 'selectMultiple';
  135. unset($data['multiple']);
  136. }
  137. $attrs = $this->_templates->formatAttributes($data);
  138. return $this->_templates->format($template, [
  139. 'name' => $name,
  140. 'attrs' => $attrs,
  141. 'content' => implode('', $options),
  142. ]);
  143. }
  144. /**
  145. * Render the contents of the select element.
  146. *
  147. * @param array $data The context for rendering a select.
  148. * @return array
  149. */
  150. protected function _renderContent($data) {
  151. $options = $data['options'];
  152. if ($options instanceof Traversable) {
  153. $options = iterator_to_array($options);
  154. }
  155. if (!empty($data['empty'])) {
  156. $value = $data['empty'] === true ? '' : $data['empty'];
  157. $options = ['' => $value] + (array)$options;
  158. }
  159. if (empty($options)) {
  160. return [];
  161. }
  162. $selected = isset($data['val']) ? $data['val'] : null;
  163. $disabled = null;
  164. if (isset($data['disabled']) && is_array($data['disabled'])) {
  165. $disabled = $data['disabled'];
  166. }
  167. return $this->_renderOptions($options, $disabled, $selected, $data['escape']);
  168. }
  169. /**
  170. * Render the contents of an optgroup element.
  171. *
  172. * @param string $label The optgroup label text
  173. * @param array $optgroup The opt group data.
  174. * @param array|null $disabled The options to disable.
  175. * @param array|string|null $selected The options to select.
  176. * @param bool $escape Toggle HTML escaping
  177. * @return string Formatted template string
  178. */
  179. protected function _renderOptgroup($label, $optgroup, $disabled, $selected, $escape) {
  180. $opts = $optgroup;
  181. $attrs = [];
  182. if (isset($optgroup['options'], $optgroup['text'])) {
  183. $opts = $optgroup['options'];
  184. $label = $optgroup['text'];
  185. $attrs = $optgroup;
  186. }
  187. $groupOptions = $this->_renderOptions($opts, $disabled, $selected, $escape);
  188. return $this->_templates->format('optgroup', [
  189. 'label' => $escape ? h($label) : $label,
  190. 'content' => implode('', $groupOptions),
  191. 'attrs' => $this->_templates->formatAttributes($attrs, ['text', 'options']),
  192. ]);
  193. }
  194. /**
  195. * Render a set of options.
  196. *
  197. * Will recursively call itself when option groups are in use.
  198. *
  199. * @param array $options The options to render.
  200. * @param array|null $disabled The options to disable.
  201. * @param array|string|null $selected The options to select.
  202. * @param bool $escape Toggle HTML escaping.
  203. * @return array Option elements.
  204. */
  205. protected function _renderOptions($options, $disabled, $selected, $escape) {
  206. $out = [];
  207. foreach ($options as $key => $val) {
  208. // Option groups
  209. $arrayVal = (is_array($val) || $val instanceof Traversable);
  210. if (
  211. (!is_int($key) && $arrayVal) ||
  212. (is_int($key) && $arrayVal && isset($val['options']))
  213. ) {
  214. $out[] = $this->_renderOptgroup($key, $val, $disabled, $selected, $escape);
  215. continue;
  216. }
  217. // Basic options
  218. $optAttrs = [
  219. 'value' => $key,
  220. 'text' => $val,
  221. ];
  222. if (is_array($val) && isset($optAttrs['text'], $optAttrs['value'])) {
  223. $optAttrs = $val;
  224. }
  225. if ($this->_isSelected($key, $selected)) {
  226. $optAttrs['selected'] = true;
  227. }
  228. if ($this->_isDisabled($key, $disabled)) {
  229. $optAttrs['disabled'] = true;
  230. }
  231. $optAttrs['escape'] = $escape;
  232. $out[] = $this->_templates->format('option', [
  233. 'value' => $escape ? h($optAttrs['value']) : $optAttrs['value'],
  234. 'text' => $escape ? h($optAttrs['text']) : $optAttrs['text'],
  235. 'attrs' => $this->_templates->formatAttributes($optAttrs, ['text', 'value']),
  236. ]);
  237. }
  238. return $out;
  239. }
  240. /**
  241. * Helper method for deciding what options are selected.
  242. *
  243. * @param string $key The key to test.
  244. * @param array|string|null $selected The selected values.
  245. * @return bool
  246. */
  247. protected function _isSelected($key, $selected) {
  248. if ($selected === null) {
  249. return false;
  250. }
  251. $isArray = is_array($selected);
  252. if (!$isArray) {
  253. return (string)$key === (string)$selected;
  254. }
  255. $strict = !is_numeric($key);
  256. return in_array((string)$key, $selected, $strict);
  257. }
  258. /**
  259. * Helper method for deciding what options are disabled.
  260. *
  261. * @param string $key The key to test.
  262. * @param array|null $disabled The disabled values.
  263. * @return bool
  264. */
  265. protected function _isDisabled($key, $disabled) {
  266. if ($disabled === null) {
  267. return false;
  268. }
  269. $strict = !is_numeric($key);
  270. return in_array((string)$key, $disabled, $strict);
  271. }
  272. /**
  273. * {@inheritDoc}
  274. */
  275. public function secureFields(array $data) {
  276. return [$data['name']];
  277. }
  278. }