TYPO3CMS  8
 All Classes Namespaces Files Functions Variables Pages
OptionViewHelper.php
Go to the documentation of this file.
1 <?php
2 namespace TYPO3\CMS\Fluid\ViewHelpers\Form\Select;
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('additionalAttributes', 'array', 'Additional tag attributes. They will be added directly to the resulting HTML tag.');
37  $this->registerArgument('data', 'array', 'Additional data-* attributes. They will each be added with a "data-" prefix.');
38  $this->registerTagAttribute('value', 'mixed', 'Value to be inserted in HTML tag - must be convertible to string!');
39  $this->registerTagAttribute('selected', 'boolean', 'If filled, overrides automatic detection of selected state for this option');
40  }
41 
45  public function render()
46  {
47  if ($this->arguments['selected'] === null) {
48  // user did not provide a tag attribute value. Determine if we need to
49  // set this attribute - or remove it entirely to prevent an empty attribute.
50  if ($this->isValueSelected($this->arguments['value'])) {
51  $this->tag->addAttribute('selected', 'selected');
52  } else {
53  $this->tag->removeAttribute('selected');
54  }
55  }
56  $childContent = $this->renderChildren();
57  $this->tag->setContent($childContent);
58  if (!isset($this->arguments['value'])) {
59  $this->tag->addAttribute('value', $childContent);
60  }
61  $parentRequestedFormTokenFieldName = $this->viewHelperVariableContainer->get(
62  SelectViewHelper::class,
63  'registerFieldNameForFormTokenGeneration'
64  );
65  if ($parentRequestedFormTokenFieldName) {
66  // parent (select field) has requested this option must add one more
67  // entry in the token generation registry for one additional potential
68  // value of the field. Happens when "multiple" is true on parent.
69  $this->registerFieldNameForFormTokenGeneration($parentRequestedFormTokenFieldName);
70  }
71  return $this->tag->render();
72  }
73 
78  protected function isValueSelected($value)
79  {
80  $selectedValue = $this->viewHelperVariableContainer->get(SelectViewHelper::class, 'selectedValue');
81  if (is_array($selectedValue)) {
82  return in_array($value, $selectedValue);
83  } elseif ($selectedValue instanceof \Iterator) {
84  return in_array($value, iterator_to_array($selectedValue));
85  }
86  return $value == $selectedValue;
87  }
88 }
registerTagAttribute($name, $type, $description, $required=false, $default=null)