Advertisement
Guest User

Untitled

a guest
Nov 9th, 2016
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.53 KB | None | 0 0
  1. <?php
  2.  
  3.  
  4.  
  5. namespace SoftUniBlogBundle\Controller\Admin;
  6.  
  7.  
  8. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  9. use SoftUniBlogBundle\Entity\Role;
  10. use SoftUniBlogBundle\Entity\User;
  11. use SoftUniBlogBundle\Form\UserEditType;
  12. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  13. use Symfony\Component\HttpFoundation\Request;
  14.  
  15. /**
  16. * @Route("/admin/users")
  17. *
  18. * Class UserController
  19. * @package SoftUniBlogBundle\Controller
  20. */
  21. class UserController extends Controller
  22. {
  23. /**
  24. * @Route("/", name="admin_users")
  25. * @return \Symfony\Component\HttpFoundation\Response
  26. */
  27. public function listUsers()
  28. {
  29. $users = $this->getDoctrine()->getRepository(User::class)->findAll();
  30. return $this->render("admin/user/list.html.twig", ['users'=>$users]);
  31.  
  32. }
  33.  
  34. /**
  35. * @Route("/edit/{id}", name="admin_user_edit")
  36. *
  37. * @param $id
  38. * @param Request $request
  39. * @return \Symfony\Component\HttpFoundation\Response
  40. */
  41. public function editUser($id, Request $request)
  42. {
  43. $user =$this->getDoctrine()->getRepository(User::class)->find($id);
  44. if($user === null){
  45. return $this->redirectToRoute("admin_users");
  46. }
  47. $originalPassword = $user->getPassword();
  48.  
  49. $form =$this->createForm(UserEditType::class, $user);
  50. $form->handleRequest($request);
  51.  
  52.  
  53.  
  54. if($form->isSubmitted() && $form->isValid()){
  55. $em = $this->getDoctrine()->getEntityManager();
  56. $em->persist($user);
  57. $em->flush();
  58. return $this->redirectToRoute('admin_users');
  59. }
  60.  
  61. if ($form->isSubmitted() && $form->isValid()){
  62.  
  63. $rolesRequest = $user->getRoles();
  64. $roleRepository = $this->getDoctrine()->getRepository(Role::class);
  65. $roles=[];
  66.  
  67. foreach ($rolesRequest as $roleName) {
  68. $roles[]= $roleRepository->findOneBy(['name' => $roleName]);
  69. }
  70. $user->setRoles($roles);
  71. }
  72.  
  73.  
  74. if ($user->getPassword()) {
  75. $password = $this->get('security.password_encoder')
  76. ->encodePassword($user,$user->getPassword());
  77. $user->setPassword($password);
  78.  
  79. }
  80. else {
  81. $user->setPassword($originalPassword);
  82. }
  83. $em = $this->getDoctrine()->getEntityManager();
  84.  
  85.  
  86.  
  87. return $this->render('admin/user/edit.html.twig', ['user' =>$user,
  88. 'form'=> $form->createView()]);
  89.  
  90.  
  91. }
  92.  
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement