TYPO3 CMS  TYPO3_8-7
OptionViewHelper.php
Go to the documentation of this file.
1 <?php
3 
4 /*
5  * This file is part of the TYPO3 CMS project.
6  *
7  * It is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU General Public License, either version 2
9  * of the License, or any later version.
10  *
11  * For the full copyright and license information, please read the
12  * LICENSE.txt file that was distributed with this source code.
13  *
14  * The TYPO3 project - inspiring people to share!
15  */
17 
24 {
28  protected $tagName = 'option';
29 
33  public function initializeArguments()
34  {
36  $this->registerArgument('selected', 'boolean', 'If set, overrides automatic detection of selected state for this option.');
37  $this->registerArgument('additionalAttributes', 'array', 'Additional tag attributes. They will be added directly to the resulting HTML tag.');
38  $this->registerArgument('data', 'array', 'Additional data-* attributes. They will each be added with a "data-" prefix.');
39  $this->registerTagAttribute('value', 'mixed', 'Value to be inserted in HTML tag - must be convertible to string!');
40  }
41 
45  public function render()
46  {
47  if ($this->arguments['selected'] ?? $this->isValueSelected($this->arguments['value'])) {
48  $this->tag->addAttribute('selected', 'selected');
49  }
50  $childContent = $this->renderChildren();
51  $this->tag->setContent($childContent);
52  if (!isset($this->arguments['value'])) {
53  $this->tag->addAttribute('value', $childContent);
54  }
55  $parentRequestedFormTokenFieldName = $this->viewHelperVariableContainer->get(
56  SelectViewHelper::class,
57  'registerFieldNameForFormTokenGeneration'
58  );
59  if ($parentRequestedFormTokenFieldName) {
60  // parent (select field) has requested this option must add one more
61  // entry in the token generation registry for one additional potential
62  // value of the field. Happens when "multiple" is true on parent.
63  $this->registerFieldNameForFormTokenGeneration($parentRequestedFormTokenFieldName);
64  }
65  return $this->tag->render();
66  }
67 
72  protected function isValueSelected($value)
73  {
74  $selectedValue = $this->viewHelperVariableContainer->get(SelectViewHelper::class, 'selectedValue');
75  if (is_array($selectedValue)) {
76  return in_array($value, $selectedValue);
77  }
78  if ($selectedValue instanceof \Iterator) {
79  return in_array($value, iterator_to_array($selectedValue));
80  }
81  return $value == $selectedValue;
82  }
83 }
registerTagAttribute($name, $type, $description, $required=false, $default=null)