[BUGFIX] Submitted form data has precedence over value argument
[Packages/TYPO3.CMS.git] / typo3 / sysext / fluid / Classes / ViewHelpers / Form / SelectViewHelper.php
1 <?php
2 namespace TYPO3\CMS\Fluid\ViewHelpers\Form;
3
4 /* *
5 * This script is backported from the TYPO3 Flow package "TYPO3.Fluid". *
6 * *
7 * It is free software; you can redistribute it and/or modify it under *
8 * the terms of the GNU Lesser General Public License, either version 3 *
9 * of the License, or (at your option) any later version. *
10 * *
11 * The TYPO3 project - inspiring people to share! *
12 * */
13 /**
14 * This view helper generates a <select> dropdown list for the use with a form.
15 *
16 * = Basic usage =
17 *
18 * The most straightforward way is to supply an associative array as the "options" parameter.
19 * The array key is used as option key, and the value is used as human-readable name.
20 *
21 * <code title="Basic usage">
22 * <f:form.select name="paymentOptions" options="{payPal: 'PayPal International Services', visa: 'VISA Card'}" />
23 * </code>
24 *
25 * = Pre-select a value =
26 *
27 * To pre-select a value, set "value" to the option key which should be selected.
28 * <code title="Default value">
29 * <f:form.select name="paymentOptions" options="{payPal: 'PayPal International Services', visa: 'VISA Card'}" value="visa" />
30 * </code>
31 * Generates a dropdown box like above, except that "VISA Card" is selected.
32 *
33 * If the select box is a multi-select box (multiple="true"), then "value" can be an array as well.
34 *
35 * = Usage on domain objects =
36 *
37 * If you want to output domain objects, you can just pass them as array into the "options" parameter.
38 * To define what domain object value should be used as option key, use the "optionValueField" variable. Same goes for optionLabelField.
39 * If neither is given, the Identifier (UID/uid) and the __toString() method are tried as fallbacks.
40 *
41 * If the optionValueField variable is set, the getter named after that value is used to retrieve the option key.
42 * If the optionLabelField variable is set, the getter named after that value is used to retrieve the option value.
43 *
44 * If the prependOptionLabel variable is set, an option item is added in first position, bearing an empty string or -
45 * If provided, the value of the prependOptionValue variable as value.
46 *
47 * <code title="Domain objects">
48 * <f:form.select name="users" options="{userArray}" optionValueField="id" optionLabelField="firstName" />
49 * </code>
50 * In the above example, the userArray is an array of "User" domain objects, with no array key specified.
51 *
52 * So, in the above example, the method $user->getId() is called to retrieve the key, and $user->getFirstName() to retrieve the displayed value of each entry.
53 *
54 * The "value" property now expects a domain object, and tests for object equivalence.
55 *
56 * @api
57 */
58 class SelectViewHelper extends \TYPO3\CMS\Fluid\ViewHelpers\Form\AbstractFormFieldViewHelper {
59
60 /**
61 * @var string
62 */
63 protected $tagName = 'select';
64
65 /**
66 * @var mixed
67 */
68 protected $selectedValue = NULL;
69
70 /**
71 * Initialize arguments.
72 *
73 * @return void
74 * @api
75 */
76 public function initializeArguments() {
77 parent::initializeArguments();
78 $this->registerUniversalTagAttributes();
79 $this->registerTagAttribute('multiple', 'string', 'if set, multiple select field');
80 $this->registerTagAttribute('size', 'string', 'Size of input field');
81 $this->registerTagAttribute('disabled', 'string', 'Specifies that the input element should be disabled when the page loads');
82 $this->registerArgument('options', 'array', 'Associative array with internal IDs as key, and the values are displayed in the select box', TRUE);
83 $this->registerArgument('optionValueField', 'string', 'If specified, will call the appropriate getter on each object to determine the value.');
84 $this->registerArgument('optionLabelField', 'string', 'If specified, will call the appropriate getter on each object to determine the label.');
85 $this->registerArgument('sortByOptionLabel', 'boolean', 'If true, List will be sorted by label.', FALSE, FALSE);
86 $this->registerArgument('selectAllByDefault', 'boolean', 'If specified options are selected if none was set before.', FALSE, FALSE);
87 $this->registerArgument('errorClass', 'string', 'CSS class to set if there are errors for this view helper', FALSE, 'f3-form-error');
88 $this->registerArgument('prependOptionLabel', 'string', 'If specified, will provide an option at first position with the specified label.');
89 $this->registerArgument('prependOptionValue', 'string', 'If specified, will provide an option at first position with the specified value.');
90 }
91
92 /**
93 * Render the tag.
94 *
95 * @return string rendered tag.
96 * @api
97 */
98 public function render() {
99 $name = $this->getName();
100 if ($this->hasArgument('multiple')) {
101 $name .= '[]';
102 }
103 $this->tag->addAttribute('name', $name);
104 $options = $this->getOptions();
105 if (empty($options)) {
106 $options = array('' => '');
107 }
108 $this->tag->setContent($this->renderOptionTags($options));
109 $this->addAdditionalIdentityPropertiesIfNeeded();
110 $this->setErrorClassAttribute();
111 $content = '';
112 // register field name for token generation.
113 // in case it is a multi-select, we need to register the field name
114 // as often as there are elements in the box
115 if ($this->hasArgument('multiple') && $this->arguments['multiple'] !== '') {
116 $content .= $this->renderHiddenFieldForEmptyValue();
117 for ($i = 0; $i < count($options); $i++) {
118 $this->registerFieldNameForFormTokenGeneration($name);
119 }
120 } else {
121 $this->registerFieldNameForFormTokenGeneration($name);
122 }
123 $content .= $this->tag->render();
124 return $content;
125 }
126
127 /**
128 * Render the option tags.
129 *
130 * @param array $options the options for the form.
131 * @return string rendered tags.
132 */
133 protected function renderOptionTags($options) {
134 $output = '';
135 if ($this->hasArgument('prependOptionLabel')) {
136 $value = $this->hasArgument('prependOptionValue') ? $this->arguments['prependOptionValue'] : '';
137 $label = $this->arguments['prependOptionLabel'];
138 $output .= $this->renderOptionTag($value, $label, FALSE) . LF;
139 }
140 foreach ($options as $value => $label) {
141 $isSelected = $this->isSelected($value);
142 $output .= $this->renderOptionTag($value, $label, $isSelected) . LF;
143 }
144 return $output;
145 }
146
147 /**
148 * Render the option tags.
149 *
150 * @return array an associative array of options, key will be the value of the option tag
151 */
152 protected function getOptions() {
153 if (!is_array($this->arguments['options']) && !$this->arguments['options'] instanceof \Traversable) {
154 return array();
155 }
156 $options = array();
157 $optionsArgument = $this->arguments['options'];
158 foreach ($optionsArgument as $key => $value) {
159 if (is_object($value) || is_array($value)) {
160 if ($this->hasArgument('optionValueField')) {
161 $key = \TYPO3\CMS\Extbase\Reflection\ObjectAccess::getPropertyPath($value, $this->arguments['optionValueField']);
162 if (is_object($key)) {
163 if (method_exists($key, '__toString')) {
164 $key = (string)$key;
165 } else {
166 throw new \TYPO3\CMS\Fluid\Core\ViewHelper\Exception('Identifying value for object of class "' . get_class($value) . '" was an object.', 1247827428);
167 }
168 }
169 // @todo use $this->persistenceManager->isNewObject() once it is implemented
170 } elseif ($this->persistenceManager->getIdentifierByObject($value) !== NULL) {
171 $key = $this->persistenceManager->getIdentifierByObject($value);
172 } elseif (method_exists($value, '__toString')) {
173 $key = (string)$value;
174 } else {
175 throw new \TYPO3\CMS\Fluid\Core\ViewHelper\Exception('No identifying value for object of class "' . get_class($value) . '" found.', 1247826696);
176 }
177 if ($this->hasArgument('optionLabelField')) {
178 $value = \TYPO3\CMS\Extbase\Reflection\ObjectAccess::getPropertyPath($value, $this->arguments['optionLabelField']);
179 if (is_object($value)) {
180 if (method_exists($value, '__toString')) {
181 $value = (string)$value;
182 } else {
183 throw new \TYPO3\CMS\Fluid\Core\ViewHelper\Exception('Label value for object of class "' . get_class($value) . '" was an object without a __toString() method.', 1247827553);
184 }
185 }
186 } elseif (method_exists($value, '__toString')) {
187 $value = (string)$value;
188 // @todo use $this->persistenceManager->isNewObject() once it is implemented
189 } elseif ($this->persistenceManager->getIdentifierByObject($value) !== NULL) {
190 $value = $this->persistenceManager->getIdentifierByObject($value);
191 }
192 }
193 $options[$key] = $value;
194 }
195 if ($this->arguments['sortByOptionLabel']) {
196 asort($options, SORT_LOCALE_STRING);
197 }
198 return $options;
199 }
200
201 /**
202 * Render the option tags.
203 *
204 * @param mixed $value Value to check for
205 * @return bool TRUE if the value should be marked a s selected; FALSE otherwise
206 */
207 protected function isSelected($value) {
208 $selectedValue = $this->getSelectedValue();
209 if ($value === $selectedValue || (string)$value === $selectedValue) {
210 return TRUE;
211 }
212 if ($this->hasArgument('multiple')) {
213 if (is_null($selectedValue) && $this->arguments['selectAllByDefault'] === TRUE) {
214 return TRUE;
215 } elseif (is_array($selectedValue) && in_array($value, $selectedValue)) {
216 return TRUE;
217 }
218 }
219 return FALSE;
220 }
221
222 /**
223 * Retrieves the selected value(s)
224 *
225 * @return mixed value string or an array of strings
226 */
227 protected function getSelectedValue() {
228 $this->setRespectSubmittedDataValue(TRUE);
229 $value = $this->getValueAttribute();
230 if (!is_array($value) && !$value instanceof \Traversable) {
231 return $this->getOptionValueScalar($value);
232 }
233 $selectedValues = array();
234 foreach ($value as $selectedValueElement) {
235 $selectedValues[] = $this->getOptionValueScalar($selectedValueElement);
236 }
237 return $selectedValues;
238 }
239
240 /**
241 * Get the option value for an object
242 *
243 * @param mixed $valueElement
244 * @return string
245 */
246 protected function getOptionValueScalar($valueElement) {
247 if (is_object($valueElement)) {
248 if ($this->hasArgument('optionValueField')) {
249 return \TYPO3\CMS\Extbase\Reflection\ObjectAccess::getPropertyPath($valueElement, $this->arguments['optionValueField']);
250 } else {
251 // @todo use $this->persistenceManager->isNewObject() once it is implemented
252 if ($this->persistenceManager->getIdentifierByObject($valueElement) !== NULL) {
253 return $this->persistenceManager->getIdentifierByObject($valueElement);
254 } else {
255 return (string)$valueElement;
256 }
257 }
258 } else {
259 return $valueElement;
260 }
261 }
262
263 /**
264 * Render one option tag
265 *
266 * @param string $value value attribute of the option tag (will be escaped)
267 * @param string $label content of the option tag (will be escaped)
268 * @param bool $isSelected specifies wheter or not to add selected attribute
269 * @return string the rendered option tag
270 */
271 protected function renderOptionTag($value, $label, $isSelected) {
272 $output = '<option value="' . htmlspecialchars($value) . '"';
273 if ($isSelected) {
274 $output .= ' selected="selected"';
275 }
276 $output .= '>' . htmlspecialchars($label) . '</option>';
277 return $output;
278 }
279
280 }