2 namespace TYPO3\CMS\Backend\Form\Element
;
4 /***************************************************************
7 * (c) 2007-2013 Andreas Wolf <andreas.wolf@ikt-werk.de>
10 * This script is part of the TYPO3 project. The TYPO3 project is
11 * free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
18 * A copy is found in the textfile GPL.txt and important notices to the license
19 * from the author is found in LICENSE.txt distributed with these scripts.
22 * This script is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * This copyright notice MUST APPEAR in all copies of the script!
28 ***************************************************************/
30 use TYPO3\CMS\Backend\Utility\BackendUtility
;
31 use TYPO3\CMS\Core\Utility\GeneralUtility
;
34 * TCEforms wizard for rendering an AJAX selector for records
36 * @author Andreas Wolf <andreas.wolf@ikt-werk.de>
37 * @author Benjamin Mack <benni@typo3.org>
39 class SuggestElement
{
41 // Count the number of ajax selectors used
42 public $suggestCount = 0;
44 public $cssClass = 'typo3-TCEforms-suggest';
47 * @var \TYPO3\CMS\Backend\Form\FormEngine
52 * Initialize an instance of SuggestElement
54 * @param \TYPO3\CMS\Backend\Form\FormEngine $tceForms Reference to an TCEforms instance
57 public function init(&$tceForms) {
58 $this->TCEformsObj
= &$tceForms;
62 * Renders an ajax-enabled text field. Also adds required JS
64 * @param string $fieldname The fieldname in the form
65 * @param string $table The table we render this selector for
66 * @param string $field The field we render this selector for
67 * @param array $row The row which is currently edited
68 * @param array $config The TSconfig of the field
69 * @return string The HTML code for the selector
71 public function renderSuggestSelector($fieldname, $table, $field, array $row, array $config) {
72 $this->suggestCount++
;
73 $containerCssClass = $this->cssClass
. ' ' . $this->cssClass
. '-position-right';
74 $suggestId = 'suggest-' . $table . '-' . $field . '-' . $row['uid'];
75 if ($GLOBALS['TCA'][$table]['columns'][$field]['config']['type'] === 'flex') {
76 $fieldPattern = 'data[' . $table . '][' . $row['uid'] . '][';
77 $flexformField = str_replace($fieldPattern, '', $fieldname);
78 $flexformField = substr($flexformField, 0, -1);
79 $field = str_replace(array(']['), '|', $flexformField);
82 <div class="' . $containerCssClass . '" id="' . $suggestId . '">
83 <input type="text" id="' . $fieldname . 'Suggest" value="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.findRecord') . '" class="' . $this->cssClass
. '-search" />
84 <div class="' . $this->cssClass
. '-indicator" style="display: none;" id="' . $fieldname . 'SuggestIndicator">
85 <img src="' . $GLOBALS['BACK_PATH'] . 'gfx/spinner.gif" alt="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:alttext.suggestSearching') . '" />
87 <div class="' . $this->cssClass
. '-choices" style="display: none;" id="' . $fieldname . 'SuggestChoices"></div>
90 // Get minimumCharacters from TCA
91 if (isset($config['fieldConf']['config']['wizards']['suggest']['default']['minimumCharacters'])) {
92 $minChars = intval($config['fieldConf']['config']['wizards']['suggest']['default']['minimumCharacters']);
94 // Overwrite it with minimumCharacters from TSConfig (TCEFORM) if given
95 if (isset($config['fieldTSConfig']['suggest.']['default.']['minimumCharacters'])) {
96 $minChars = intval($config['fieldTSConfig']['suggest.']['default.']['minimumCharacters']);
98 $minChars = $minChars > 0 ?
$minChars : 2;
99 // Replace "-" with ucwords for the JS object name
100 $jsObj = str_replace(' ', '', ucwords(str_replace('-', ' ', GeneralUtility
::strtolower($suggestId))));
101 $this->TCEformsObj
->additionalJS_post
[] = '
102 var ' . $jsObj . ' = new TCEForms.Suggest("' . $fieldname . '", "' . $table . '", "' . $field . '", "' . $row['uid'] . '", ' . $row['pid'] . ', ' . $minChars . ');
103 ' . $jsObj . '.defaultValue = "' . GeneralUtility
::slashJS($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.findRecord')) . '";
109 * Search a data structure array recursively -- including within nested
110 * (repeating) elements -- for a particular field config.
112 * @param array $dataStructure The data structure
113 * @param string $fieldName The field name
116 protected function getNestedDsFieldConfig(array $dataStructure, $fieldName) {
117 $fieldConfig = array();
118 $elements = $dataStructure['ROOT']['el'] ?
$dataStructure['ROOT']['el'] : $dataStructure['el'];
119 if (is_array($elements)) {
120 foreach ($elements as $k => $ds) {
121 if ($k === $fieldName) {
122 $fieldConfig = $ds['TCEforms']['config'];
124 } elseif (isset($ds['el'][$fieldName]['TCEforms']['config'])) {
125 $fieldConfig = $ds['el'][$fieldName]['TCEforms']['config'];
128 $fieldConfig = $this->getNestedDsFieldConfig($ds, $fieldName);
136 * Ajax handler for the "suggest" feature in TCEforms.
138 * @param array $params The parameters from the AJAX call
139 * @param \TYPO3\CMS\Core\Http\AjaxRequestHandler $ajaxObj The AJAX object representing the AJAX call
142 public function processAjaxRequest($params, &$ajaxObj) {
143 // Get parameters from $_GET/$_POST
144 $search = GeneralUtility
::_GP('value');
145 $table = GeneralUtility
::_GP('table');
146 $field = GeneralUtility
::_GP('field');
147 $uid = GeneralUtility
::_GP('uid');
148 $pageId = GeneralUtility
::_GP('pid');
149 // If the $uid is numeric, we have an already existing element, so get the
150 // TSconfig of the page itself or the element container (for non-page elements)
151 // otherwise it's a new element, so use given id of parent page (i.e., don't modify it here)
152 if (is_numeric($uid)) {
153 if ($table == 'pages') {
156 $row = BackendUtility
::getRecord($table, $uid);
157 $pageId = $row['pid'];
160 $TSconfig = BackendUtility
::getPagesTSconfig($pageId);
161 $queryTables = array();
162 $foreign_table_where = '';
163 $fieldConfig = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
164 $parts = explode('|', $field);
165 if ($GLOBALS['TCA'][$table]['columns'][$parts[0]]['config']['type'] === 'flex') {
166 if (is_array($row) && count($row) > 0) {
167 $flexfieldTCAConfig = $GLOBALS['TCA'][$table]['columns'][$parts[0]]['config'];
168 $flexformDSArray = BackendUtility
::getFlexFormDS($flexfieldTCAConfig, $row, $table);
169 $flexformDSArray = GeneralUtility
::resolveAllSheetsInDS($flexformDSArray);
170 $flexformElement = $parts[count($parts) - 2];
172 foreach ($flexformDSArray as $sheet) {
173 foreach ($sheet as $_ => $dataStructure) {
174 $fieldConfig = $this->getNestedDsFieldConfig($dataStructure, $flexformElement);
175 if (count($fieldConfig) > 0) {
184 $field = str_replace('|', '][', $field);
187 $wizardConfig = $fieldConfig['wizards']['suggest'];
188 if (isset($fieldConfig['allowed'])) {
189 if ($fieldConfig['allowed'] === '*') {
190 foreach ($GLOBALS['TCA'] as $tableName => $tableConfig) {
191 // TODO: Refactor function to BackendUtility
192 if (empty($tableConfig['ctrl']['hideTable'])
193 && ($GLOBALS['BE_USER']->isAdmin()
194 ||
(empty($tableConfig['ctrl']['adminOnly'])
195 && (empty($tableConfig['ctrl']['rootLevel'])
196 ||
!empty($tableConfig['ctrl']['security']['ignoreRootLevelRestriction']))))
198 $queryTables[] = $tableName;
201 unset($tableName, $tableConfig);
203 $queryTables = \TYPO3\CMS\Core\Utility\GeneralUtility
::trimExplode(',', $fieldConfig['allowed']);
205 } elseif (isset($fieldConfig['foreign_table'])) {
206 $queryTables = array($fieldConfig['foreign_table']);
207 $foreign_table_where = $fieldConfig['foreign_table_where'];
208 // strip ORDER BY clause
209 $foreign_table_where = trim(preg_replace('/ORDER[[:space:]]+BY.*/i', '', $foreign_table_where));
211 $resultRows = array();
212 // fetch the records for each query table. A query table is a table from which records are allowed to
213 // be added to the TCEForm selector, originally fetched from the "allowed" config option in the TCA
214 foreach ($queryTables as $queryTable) {
215 // if the table does not exist, skip it
216 if (!is_array($GLOBALS['TCA'][$queryTable]) ||
!count($GLOBALS['TCA'][$queryTable])) {
219 $config = (array) $wizardConfig['default'];
220 if (is_array($wizardConfig[$queryTable])) {
221 $config = GeneralUtility
::array_merge_recursive_overrule($config, $wizardConfig[$queryTable]);
223 // merge the configurations of different "levels" to get the working configuration for this table and
224 // field (i.e., go from the most general to the most special configuration)
225 if (is_array($TSconfig['TCEFORM.']['suggest.']['default.'])) {
226 $config = GeneralUtility
::array_merge_recursive_overrule($config, $TSconfig['TCEFORM.']['suggest.']['default.']);
228 if (is_array($TSconfig['TCEFORM.']['suggest.'][$queryTable . '.'])) {
229 $config = GeneralUtility
::array_merge_recursive_overrule($config, $TSconfig['TCEFORM.']['suggest.'][$queryTable . '.']);
231 // use $table instead of $queryTable here because we overlay a config
232 // for the input-field here, not for the queried table
233 if (is_array($TSconfig['TCEFORM.'][$table . '.'][$field . '.']['suggest.']['default.'])) {
234 $config = GeneralUtility
::array_merge_recursive_overrule($config, $TSconfig['TCEFORM.'][$table . '.'][$field . '.']['suggest.']['default.']);
236 if (is_array($TSconfig['TCEFORM.'][$table . '.'][$field . '.']['suggest.'][$queryTable . '.'])) {
237 $config = GeneralUtility
::array_merge_recursive_overrule($config, $TSconfig['TCEFORM.'][$table . '.'][$field . '.']['suggest.'][$queryTable . '.']);
240 if (!isset($config['addWhere']) && $foreign_table_where) {
241 $config['addWhere'] = $foreign_table_where;
243 if (isset($config['addWhere'])) {
244 $config['addWhere'] = strtr(' ' . $config['addWhere'], array(
245 '###THIS_UID###' => intval($uid),
246 '###CURRENT_PID###' => intval($pageId)
249 // instantiate the class that should fetch the records for this $queryTable
250 $receiverClassName = $config['receiverClass'];
251 if (!class_exists($receiverClassName)) {
252 $receiverClassName = 'TYPO3\\CMS\\Backend\\Form\\Element\\SuggestDefaultReceiver';
254 $receiverObj = GeneralUtility
::makeInstance($receiverClassName, $queryTable, $config);
255 $params = array('value' => $search);
256 $rows = $receiverObj->queryTable($params);
260 $resultRows = GeneralUtility
::array_merge($resultRows, $rows);
263 $listItems = array();
264 if (count($resultRows) > 0) {
265 // traverse all found records and sort them
267 foreach ($resultRows as $key => $row) {
268 $rowsSort[$key] = $row['text'];
271 $rowsSort = array_keys($rowsSort);
272 // Limit the number of items in the result list
273 $maxItems = $config['maxItemsInResultList'] ?
$config['maxItemsInResultList'] : 10;
274 $maxItems = min(count($resultRows), $maxItems);
275 // put together the selector entry
276 for ($i = 0; $i < $maxItems; $i++
) {
277 $row = $resultRows[$rowsSort[$i]];
278 $rowId = $row['table'] . '-' . $row['uid'] . '-' . $table . '-' . $uid . '-' . $field;
279 $listItems[] = '<li' . ($row['class'] != '' ?
' class="' . $row['class'] . '"' : '') . ' id="' . $rowId . '"' . ($row['style'] != '' ?
' style="' . $row['style'] . '"' : '') . '>' . $row['sprite'] . $row['text'] . '</li>';
282 if (count($listItems) > 0) {
283 $list = implode('', $listItems);
285 $list = '<li class="suggest-noresults"><i>' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.noRecordFound') . '</i></li>';
287 $list = '<ul class="' . $this->cssClass
. '-resultlist">' . $list . '</ul>';
288 $ajaxObj->addContent(0, $list);