chill-bundles/src/Bundle/ChillPersonBundle/Controller/AccompanyingCourseCommentController.php

87 lines
3.3 KiB
PHP

<?php
namespace Chill\PersonBundle\Controller;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Form\AccompanyingCourseCommentType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class AccompanyingCourseCommentController extends Controller
{
/**
* Comments page of Accompanying Course section.
*
* @Route("/{_locale}/parcours/{accompanying_period_id}/comments", name="chill_person_accompanying_period_comment_list")
* @ParamConverter("accompanyingCourse", options={"id": "accompanying_period_id"})
*/
public function commentAction(AccompanyingPeriod $accompanyingCourse, Request $request): Response
{
$newComment = new AccompanyingPeriod\Comment();
$newComment->setAccompanyingPeriod($accompanyingCourse);
$form = $this->createCommentForm($newComment, 'new');
if ($request->query->has('edit')) {
foreach ($accompanyingCourse->getComments() as $comment) {
if ($comment->getId() === $request->query->getInt('edit')) {
$editForm = $this->createCommentForm($comment, 'edit');
$commentEditId = $comment->getId();
}
}
$pinnedComment = $accompanyingCourse->getPinnedComment();
if ($pinnedComment->getId() === $request->query->getInt('edit')) {
$editForm = $this->createCommentForm($pinnedComment, 'edit');
$commentEditId = $pinnedComment->getId();
}
}
if ($request->getMethod() === Request::METHOD_POST) {
if (array_key_exists('edit', $request->request->all()[$editForm->getName()])) {
$currentForm = $editForm->handleRequest($request);
$isEditingNew = false;
} else {
$currentForm = $form->handleRequest($request);
$isEditingNew = true;
}
if ($currentForm->isSubmitted() && $currentForm->isValid()) {
$em = $this->getDoctrine()->getManager();
if ($isEditingNew) {
$em->persist($newComment);
}
$em->flush();
}
return $this->redirectToRoute('chill_person_accompanying_period_comment_list', [
'accompanying_period_id' => $accompanyingCourse->getId()
]);
}
return $this->render('@ChillPerson/AccompanyingCourse/comment_list.html.twig', [
'accompanyingCourse' => $accompanyingCourse,
'form' => $form->createView(),
'edit_form' => isset($editForm) ? $editForm->createView() : null,
'commentEditId' => $commentEditId ?? null,
]);
}
private function createCommentForm(AccompanyingPeriod\Comment $comment, string $step): FormInterface
{
$form = $this->createForm(AccompanyingCourseCommentType::class, $comment);
if ('edit' === $step) {
$form->add('edit', HiddenType::class, ['mapped' => false ]);
}
return $form;
}
}