get('session'); if (null === $session->get('user')) { return $this->redirectToRoute('home'); } $formBuilder = $this->createFormBuilder(); $formBuilder->add('text', \Symfony\Component\Form\Extension\Core\Type\TextType::class) ->add('username', \Symfony\Component\Form\Extension\Core\Type\TextType::class) ->setAction($this->generateUrl('private_discussions')); $form = $formBuilder->getForm(); $em = $this->getDoctrine()->getManager(); $repo_user = $em->getRepository(User::class); $user = $repo_user->findOneBy(array('username' => $session->get("user"))); $private_discussions = array(); foreach ($user->getPrivateDiscussions() as $pd) { $participants = $pd->getParticipants(); if ($participants[0] == $user) { $participant = $participants[1]; } else { $participant = $participants[0]; } array_push($private_discussions, array($pd->getId() => $participant->getUsername())); } if ($request->getMethod() == 'POST') { $form->handleRequest($request); if ($form->isValid()) { $recept = $repo_user->findOneBy(array('username' => $form->get('username')->getData())); if (!$recept) { return new Response("Profil non existant"); } $disc_found = false; foreach ($user->getPrivateDiscussions() as $disc) { if(in_array($recept, $disc->getParticipants()->getValues())) { $disc_found = true; break; } } if ($disc_found) { return new Response("Discussion existante"); } $discussion = new PrivateDiscussion(); $discussion->addParticipant($user); $discussion->addParticipant($recept); $dm = new PrivateMessage(); $dm->setSender($user); $dm->setText($form->get('text')->getData()); $discussion->addPrivateMessage($dm); $em->persist($dm); $em->persist($discussion); $em->flush(); } } return $this->render('private_discussions/index.html.twig', [ 'controller_name' => 'PrivateDiscussionsController', 'form' => $form->createView(), 'private_discussions' => $private_discussions, 'username' => $session->get('user'), ]); } }