self::SEASON_CODE_REGEX, 'quiz' => Requirement::UUID, 'question' => Requirement::UUID], )] public function edit(Season $season, Quiz $quiz, Question $question, Request $request): Response { if ($question->quiz !== $quiz || $quiz->season !== $season) { throw new NotFoundHttpException(); } $isModalRequest = $request->headers->has('X-Modal-Request'); $form = $this->createForm(QuestionFormType::class, $question); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $this->applyAnswerOrdering($question); $this->em->flush(); $this->addFlash(FlashType::Success, $this->translator->trans('Question updated')); if ($isModalRequest) { return new Response('', Response::HTTP_NO_CONTENT); } return $this->redirectToRoute('tvdt_backoffice_quiz_overview', [ 'seasonCode' => $season->seasonCode, 'quiz' => $quiz->id, ]); } $template = $isModalRequest ? 'backoffice/quiz/_question_form_body.html.twig' : 'backoffice/quiz/question_form.html.twig'; $response = $this->render($template, [ 'season' => $season, 'quiz' => $quiz, 'question' => $question, 'form' => $form, 'isModal' => $isModalRequest, ]); if ($form->isSubmitted()) { $response->setStatusCode(Response::HTTP_UNPROCESSABLE_ENTITY); } return $response; } #[Route( '/backoffice/season/{seasonCode:season}/quiz/{quiz}/question/{question}/view', name: 'tvdt_backoffice_quiz_question_view', requirements: ['seasonCode' => self::SEASON_CODE_REGEX, 'quiz' => Requirement::UUID, 'question' => Requirement::UUID], )] public function view(Season $season, Quiz $quiz, Question $question): Response { if ($question->quiz !== $quiz || $quiz->season !== $season) { throw new NotFoundHttpException(); } return $this->render('backoffice/quiz/_question_detail_body.html.twig', [ 'question' => $question, ]); } #[IsCsrfTokenValid('question_reorder')] #[IsGranted(SeasonVoter::MODIFY_QUIZ_CONTENT, subject: 'quiz')] #[Route( '/backoffice/season/{seasonCode:season}/quiz/{quiz}/questions/reorder', name: 'tvdt_backoffice_quiz_questions_reorder', requirements: ['seasonCode' => self::SEASON_CODE_REGEX, 'quiz' => Requirement::UUID], methods: ['POST'], )] public function reorder(Season $season, Quiz $quiz, Request $request): Response { if ($quiz->season !== $season) { throw new NotFoundHttpException(); } /** @var list $ordering */ $ordering = $request->request->all('ordering'); $questionsById = []; foreach ($quiz->questions as $question) { $questionsById[$question->id->toString()] = $question; } foreach ($ordering as $questionId) { if (!isset($questionsById[$questionId])) { throw new BadRequestHttpException(\sprintf('Unknown question id: %s', $questionId)); } } $position = 1; foreach ($ordering as $questionId) { $questionsById[$questionId]->ordering = $position++; } $this->em->flush(); return new Response('', Response::HTTP_NO_CONTENT); } private function applyAnswerOrdering(Question $question): void { $ordering = 1; foreach ($question->answers as $answer) { $answer->ordering = $ordering++; } } }