[BUGFIX] MM Relation with add wizard resets the MM Relation
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Controller / Wizard / AddController.php
1 <?php
2 namespace TYPO3\CMS\Backend\Controller\Wizard;
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 */
16
17 use Psr\Http\Message\ResponseInterface;
18 use Psr\Http\Message\ServerRequestInterface;
19 use TYPO3\CMS\Backend\Form\FormDataCompiler;
20 use TYPO3\CMS\Backend\Form\FormDataGroup\TcaDatabaseRecord;
21 use TYPO3\CMS\Backend\Utility\BackendUtility;
22 use TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools;
23 use TYPO3\CMS\Core\DataHandling\DataHandler;
24 use TYPO3\CMS\Core\Utility\GeneralUtility;
25 use TYPO3\CMS\Core\Utility\HttpUtility;
26 use TYPO3\CMS\Core\Utility\MathUtility;
27
28 /**
29 * Script Class for adding new items to a group/select field. Performs proper redirection as needed.
30 * Script is typically called after new child record was added and then adds the new child to select value of parent.
31 */
32 class AddController extends AbstractWizardController
33 {
34 /**
35 * Content accumulation for the module.
36 *
37 * @var string
38 */
39 public $content;
40
41 /**
42 * If set, the DataHandler class is loaded and used to add the returning ID to the parent record.
43 *
44 * @var int
45 */
46 public $processDataFlag = 0;
47
48 /**
49 * Create new record -pid (pos/neg). If blank, return immediately
50 *
51 * @var int
52 */
53 public $pid;
54
55 /**
56 * The parent table we are working on.
57 *
58 * @var string
59 */
60 public $table;
61
62 /**
63 * Loaded with the created id of a record FormEngine returns ...
64 *
65 * @var int
66 */
67 public $id;
68
69 /**
70 * Wizard parameters, coming from TCEforms linking to the wizard.
71 *
72 * @var array
73 */
74 public $P;
75
76 /**
77 * Information coming back from the FormEngine script, telling what the table/id was of the newly created record.
78 *
79 * @var array
80 */
81 public $returnEditConf;
82
83 /**
84 * Constructor
85 */
86 public function __construct()
87 {
88 parent::__construct();
89 $this->getLanguageService()->includeLLFile('EXT:lang/Resources/Private/Language/locallang_wizards.xlf');
90 $GLOBALS['SOBE'] = $this;
91
92 $this->init();
93 }
94
95 /**
96 * Initialization of the class.
97 */
98 protected function init()
99 {
100 // Init GPvars:
101 $this->P = GeneralUtility::_GP('P');
102 $this->returnEditConf = GeneralUtility::_GP('returnEditConf');
103 // Get this record
104 $record = BackendUtility::getRecord($this->P['table'], $this->P['uid']);
105 // Set table:
106 $this->table = $this->P['params']['table'];
107 // Get TSconfig for it.
108 $TSconfig = BackendUtility::getTCEFORM_TSconfig(
109 $this->P['table'],
110 is_array($record) ? $record : ['pid' => $this->P['pid']]
111 );
112 // Set [params][pid]
113 if (substr($this->P['params']['pid'], 0, 3) === '###' && substr($this->P['params']['pid'], -3) === '###') {
114 $keyword = substr($this->P['params']['pid'], 3, -3);
115 if (strpos($keyword, 'PAGE_TSCONFIG_') === 0) {
116 $this->pid = (int)$TSconfig[$this->P['field']][$keyword];
117 } else {
118 $this->pid = (int)$TSconfig['_' . $keyword];
119 }
120 } else {
121 $this->pid = (int)$this->P['params']['pid'];
122 }
123 // Return if new record as parent (not possibly/allowed)
124 if ($this->pid === '') {
125 HttpUtility::redirect(GeneralUtility::sanitizeLocalUrl($this->P['returnUrl']));
126 }
127 // Else proceed:
128 // If a new id has returned from a newly created record...
129 if ($this->returnEditConf) {
130 $editConfiguration = json_decode($this->returnEditConf, true);
131 if (is_array($editConfiguration[$this->table]) && MathUtility::canBeInterpretedAsInteger($this->P['uid'])) {
132 // Getting id and cmd from returning editConf array.
133 reset($editConfiguration[$this->table]);
134 $this->id = (int)key($editConfiguration[$this->table]);
135 $cmd = current($editConfiguration[$this->table]);
136 // ... and if everything seems OK we will register some classes for inclusion and instruct the object
137 // to perform processing later.
138 if ($this->P['params']['setValue']
139 && $cmd === 'edit'
140 && $this->id
141 && $this->P['table']
142 && $this->P['field'] && $this->P['uid']
143 ) {
144 $liveRecord = BackendUtility::getLiveVersionOfRecord($this->table, $this->id, 'uid');
145 if ($liveRecord) {
146 $this->id = $liveRecord['uid'];
147 }
148 $this->processDataFlag = 1;
149 }
150 }
151 }
152 }
153
154 /**
155 * Injects the request object for the current request or subrequest
156 * As this controller goes only through the main() method, it is rather simple for now
157 *
158 * @param ServerRequestInterface $request
159 * @param ResponseInterface $response
160 * @return ResponseInterface
161 */
162 public function mainAction(ServerRequestInterface $request, ResponseInterface $response)
163 {
164 $this->main();
165 return $response;
166 }
167
168 /**
169 * Main function
170 * Will issue a location-header, redirecting either BACK or to a new FormEngine instance...
171 */
172 public function main()
173 {
174 if ($this->returnEditConf) {
175 if ($this->processDataFlag) {
176 // Because OnTheFly can't handle MM relations with intermediate tables we use TcaDatabaseRecord here
177 // Otherwise already stored relations are overwritten with the new entry
178 /** @var TcaDatabaseRecord $formDataGroup */
179 $formDataGroup = GeneralUtility::makeInstance(TcaDatabaseRecord::class);
180 /** @var FormDataCompiler $formDataCompiler */
181 $formDataCompiler = GeneralUtility::makeInstance(FormDataCompiler::class, $formDataGroup);
182 $input = [
183 'tableName' => $this->P['table'],
184 'vanillaUid' => (int)$this->P['uid'],
185 'command' => 'edit',
186 ];
187 $result = $formDataCompiler->compile($input);
188 $currentParentRow = $result['databaseRow'];
189
190 // If that record was found (should absolutely be...), then init DataHandler and set, prepend or append
191 // the record
192 if (is_array($currentParentRow)) {
193 /** @var DataHandler $dataHandler */
194 $dataHandler = GeneralUtility::makeInstance(DataHandler::class);
195 $data = [];
196 $recordId = $this->table . '_' . $this->id;
197 // Setting the new field data:
198 // If the field is a flexForm field, work with the XML structure instead:
199 if ($this->P['flexFormPath']) {
200 // Current value of flexForm path:
201 $currentFlexFormData = GeneralUtility::xml2array($currentParentRow[$this->P['field']]);
202 /** @var FlexFormTools $flexFormTools */
203 $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
204 $currentFlexFormValue = $flexFormTools->getArrayValueByPath(
205 $this->P['flexFormPath'],
206 $currentFlexFormData
207 );
208 $insertValue = '';
209 switch ((string)$this->P['params']['setValue']) {
210 case 'set':
211 $insertValue = $recordId;
212 break;
213 case 'prepend':
214 $insertValue = $currentFlexFormValue . ',' . $recordId;
215 break;
216 case 'append':
217 $insertValue = $recordId . ',' . $currentFlexFormValue;
218 break;
219 }
220 $insertValue = implode(',', GeneralUtility::trimExplode(',', $insertValue, true));
221 $data[$this->P['table']][$this->P['uid']][$this->P['field']] = [];
222 $flexFormTools->setArrayValueByPath(
223 $this->P['flexFormPath'],
224 $data[$this->P['table']][$this->P['uid']][$this->P['field']],
225 $insertValue
226 );
227 } else {
228 // Check the row for its datatype. If it is an array it stores the relation
229 // to other rows. Implode it into a comma separated list to be able to restore the stored
230 // values after the wizard falls back to the parent record
231 $currentValue = $currentParentRow[$this->P['field']];
232 if (is_array($currentValue)) {
233 $currentValue = implode(',', array_column($currentValue, 'uid'));
234 }
235 switch ((string)$this->P['params']['setValue']) {
236 case 'set':
237 $data[$this->P['table']][$this->P['uid']][$this->P['field']] = $recordId;
238 break;
239 case 'prepend':
240 $data[$this->P['table']][$this->P['uid']][$this->P['field']] = $currentValue . ',' . $recordId;
241 break;
242 case 'append':
243 $data[$this->P['table']][$this->P['uid']][$this->P['field']] = $recordId . ',' . $currentValue;
244 break;
245 }
246 $data[$this->P['table']][$this->P['uid']][$this->P['field']] = implode(
247 ',',
248 GeneralUtility::trimExplode(
249 ',',
250 $data[$this->P['table']][$this->P['uid']][$this->P['field']],
251 true
252 )
253 );
254 }
255 // Submit the data:
256 $dataHandler->start($data, []);
257 $dataHandler->process_datamap();
258 }
259 }
260 // Return to the parent FormEngine record editing session:
261 HttpUtility::redirect(GeneralUtility::sanitizeLocalUrl($this->P['returnUrl']));
262 } else {
263 // Redirecting to FormEngine with instructions to create a new record
264 // AND when closing to return back with information about that records ID etc.
265 $redirectUrl = BackendUtility::getModuleUrl('record_edit', [
266 'returnEditConf' => 1,
267 'edit[' . $this->P['params']['table'] . '][' . $this->pid . ']' => 'new',
268 'returnUrl' => GeneralUtility::getIndpEnv('REQUEST_URI')
269 ]);
270 HttpUtility::redirect($redirectUrl);
271 }
272 }
273 }