@@ -224,20 +224,62 @@ public function newForm(?int $fromId = null): DataResponse {
224224 $ questionData ['formId ' ] = $ form ->getId ();
225225 $ newQuestion = Question::fromParams ($ questionData );
226226 $ this ->questionMapper ->insert ($ newQuestion );
227+ $ questionData ['id ' ] = $ newQuestion ->getId ();
227228
228229 if (isset ($ oldConfirmationEmailQuestionId ) && $ oldConfirmationEmailQuestionId === $ oldQuestion ->getId ()) {
229230 $ form ->setConfirmationEmailQuestionId ($ newQuestion ->getId ());
230231 }
231232
232233 // Get Options, set new QuestionId, reinsert
233234 $ options = $ this ->optionMapper ->findByQuestion ($ oldQuestion ->getId ());
235+ // Array to map old option id to new id
236+ $ optionIdMapper = [];
234237 foreach ($ options as $ oldOption ) {
235238 $ optionData = $ oldOption ->read ();
236239
240+ $ oldOptionID = $ optionData ['id ' ];
237241 unset($ optionData ['id ' ]);
238242 $ optionData ['questionId ' ] = $ newQuestion ->getId ();
239243 $ newOption = Option::fromParams ($ optionData );
240244 $ this ->optionMapper ->insert ($ newOption );
245+ $ optionIdMapper [$ oldOptionID ] = $ newOption ->getId ();
246+ }
247+ $ branches = $ questionData ['extraSettings ' ]['branches ' ] ?? null ;
248+ if (isset ($ branches ) && \is_array ($ branches ) > 0 ) {
249+ foreach ($ branches as $ branchKey => $ branch ) {
250+ if (isset ($ branch ['conditions ' ]) && \is_array ($ branch ['conditions ' ])) {
251+ foreach ($ branch ['conditions ' ] as $ conditionKey => $ cond ) {
252+ if (isset ($ cond ['optionId ' ]) && isset ($ optionIdMapper [$ cond ['optionId ' ]])) {
253+ $ branches [$ branchKey ]['conditions ' ][$ conditionKey ]['optionId ' ] = $ optionIdMapper [$ cond ['optionId ' ]];
254+ }
255+ }
256+ }
257+ if (isset ($ branch ['subQuestions ' ]) && \is_array ($ branch ['subQuestions ' ])) {
258+ foreach ($ branch ['subQuestions ' ] as $ questionKey => $ subQuestion ) {
259+ $ subQuestion ['formId ' ] = $ form ->getId ();
260+ $ subQuestion ['parentQuestionId ' ] = $ newQuestion ->getId ();
261+ $ oldOptions = $ subQuestion ['options ' ] ?? [];
262+
263+ unset($ subQuestion ['id ' ]);
264+ unset($ subQuestion ['options ' ]);
265+ unset($ subQuestion ['accept ' ]);
266+ $ newSubQuestion = Question::fromParams ($ subQuestion );
267+ $ this ->questionMapper ->insert ($ newSubQuestion );
268+ $ branches [$ branchKey ]['subQuestions ' ][$ questionKey ] = $ newSubQuestion ->read ();
269+
270+ foreach ($ oldOptions as $ optionData ) {
271+ unset($ optionData ['id ' ]);
272+ $ optionData ['questionId ' ] = $ newSubQuestion ->getId ();
273+ $ newOption = Option::fromParams ($ optionData );
274+ $ this ->optionMapper ->insert ($ newOption );
275+ }
276+ }
277+ }
278+ }
279+
280+ $ questionData ['extraSettings ' ]['branches ' ] = $ branches ;
281+ $ updatedQuestion = Question::fromParams ($ questionData );
282+ $ this ->questionMapper ->update ($ updatedQuestion );
241283 }
242284 }
243285
0 commit comments