I am currently creating a Symfony Project for School and i was just trying some things out with this Security Bundle... I was creating the Registration Controller with this php bin/console make:registration-form Command and it worked out fine. The Files got created and i got no Errors but when i am trying to go to /register they just show me my index.php all the time... if i delete index.php its always # Page not Found from my Symfony Local Server... Im just testing out so im just using this localhost Webserver from Symfony. I tested out the Route with php bin/console router:match /register and it showed green, it works and exists. But when i try going to the Site nothing happens.
namespace App\Controller;
use App\Entity\User;
use App\Form\RegistrationFormType;
use App\Repository\UserRepository;
use App\Security\EmailVerifier;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mime\Address;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
class RegistrationController extends AbstractController
{
private EmailVerifier $emailVerifier;
public function __construct(EmailVerifier $emailVerifier)
{
$this->emailVerifier = $emailVerifier;
}
#[Route('/register', name: 'app_register')]
public function register(Request $request, UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $entityManager): Response
{
$user = new User();
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password
$user->setPassword(
$userPasswordHasher->hashPassword(
$user,
$form->get('plainPassword')->getData()
)
);
$entityManager->persist($user);
$entityManager->flush();
// generate a signed url and email it to the user
$this->emailVerifier->sendEmailConfirmation('app_verify_email', $user,
(new TemplatedEmail())
->from(new Address('info#julian-schaefers.dev', 'Julian Schaefers'))
->to($user->getUserIdentifier())
->subject('Please Confirm your Email')
->htmlTemplate('registration/confirmation_email.html.twig')
);
// do anything else you need here, like send an email
return $this->redirectToRoute('_profiler_home');
}
return $this->render('registration/register.html.twig', [
'registrationForm' => $form->createView(),
]);
}
#[Route('/verify/email', name: 'app_verify_email')]
public function verifyUserEmail(Request $request, UserRepository $userRepository): Response
{
$id = $request->get('id');
if (null === $id) {
return $this->redirectToRoute('app_register');
}
$user = $userRepository->find($id);
if (null === $user) {
return $this->redirectToRoute('app_register');
}
// validate email confirmation link, sets User::isVerified=true and persists
try {
$this->emailVerifier->handleEmailConfirmation($request, $user);
} catch (VerifyEmailExceptionInterface $exception) {
$this->addFlash('verify_email_error', $exception->getReason());
return $this->redirectToRoute('app_register');
}
// #TODO Change the redirect on success and handle or remove the flash message in your templates
$this->addFlash('success', 'Your email address has been verified.');
return $this->redirectToRoute('app_register');
}
}
Related
I get the error Controller not found: service "AppBundle / Controller / TestController.php" does not exist
but i don't know how to debug it. Can someone please help me !?
Is it possible that the error comes from the routing or it is something else !?
I just want to clarify that I use Symfony 3.4.
Here is the extract from the TestController.php code
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\Task;
use AppBundle\Form\TaskType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* #Route("test/form-test")
*/
class TestController extends Controller
{
/**
* #Route("/", name="test")
*/
public function newAction(Request $request)
{
// creates a task and gives it some dummy data for this example
$task = new Task();
$task->setTask('Write a blog post');
$task->setDueDate(new \DateTime('tomorrow'));
$form = $this->get('form.factory')->createNamed('addTask', TaskType::class, $task);
$form->handleRequest($request);
$validator = $this->get('validator');
$errors = $validator->validate($form);
if (count($editErrors) > 0) {
$errorsString = (string)$editErrors;
return new Response($errorsString);
}
echo('------------------------------------------------------------------------' . $form->isSubmitted() . ' && ' . $form->isValid());
if ($form->isSubmitted() && $form->isValid()) {
// $form->getData() holds the submitted values
// but, the original `$task` variable has also been updated
$task = $form->getData();
// ... perform some action, such as saving the task to the database
// for example, if Task is a Doctrine entity, save it!
// $entityManager = $this->getDoctrine()->getManager();
// $entityManager->persist($task);
// $entityManager->flush();
return new Response('<h1>-----------------------------------------------------------------------------------OK</h1>');
}
return $this->render('default/index.html.twig', [
'form' => $form->createView(),
'errors' => $errors,
]);
}
}
thank you in advance
I'm trying to implement login form in my Symfony project. But I don't know how exactly to use my session in my controller. Actually, I don't know what is the session as a whole in Symfony.
I created the login form and it checks correctly if a user exists but when I try to save it into the session my IDE tells me that $session is Undefined variable I included "use Symfony\Component\HttpFoundation\Session\Session;"
but it didn't help. If I write $session = new Session(); $session->start(); an exception in my browser says that the session is already started. Maybe I don't use session in the right way or it can't be used in the controllers. How to fix it and how to use the session and when and where the session in Symfony starts. Here is my code.
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\User;
use Symfony\Component\HttpFoundation\Request;
use App\Form\UserType;
use App\Form\UserLoginType;
use Symfony\Component\HttpFoundation\Session\Session;
class UserController extends AbstractController
{
/**
* #Route("/EventsAndPeople/task_success", name="task_success")
*/
public function succsess()
{
return $this->render('home/Succes.html.twig');
}
/**
* #Route("/EventsAndPeople/Login", name="Login")
*/
public function login(Request $request)
{
$user = new User();
$form = $this->createForm(UserLoginType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted()) {
$notTrueUser = $form->getData();
$user = $this->getDoctrine()
->getRepository(User::class)
->findOneByPasswordAndEmailAndUsername($notTrueUser->getPassword(),$notTrueUser->getEmail(),$notTrueUser->getUsername());
if (!$user) {
throw $this->createNotFoundException(
'No product found for this email and password '
);
}
$session->set($user);
return $this->redirectToRoute('task_success');
}
return $this->render('home/LoginForm.html.twig', array(
'form' => $form->createView(),
));
}
}
I thought that if the session is already started I can use it in the controller but my IDE shows me its wrong
first of all, you must create the object of calls session
like this
$session = new Session();
or(For your issues I guess you need this statement)
$session = $request->getSession();
and then defined key with value:->
$session->set('user', $user);
I have problem when trying to dump some values, but issue is that when I use dump, it don't show any error message and don't dump any value. I have installed symfony/var-dumper.
Source code
<?php
namespace App\Controller;
use App\Form\UserType;
use App\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\VarDumper\VarDumper;
class RegistrationController extends Controller
{
/**
* #Route("/register", name="user_registration")
*/
public function registerAction(Request $request, UserPasswordEncoderInterface $passwordEncoder)
{
$user = new User();
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$password = $passwordEncoder->encodePassword($user, $user->getPlainPassword());
$user->setPassword($password);
dump($user);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
return $this->redirectToRoute('number', array('slug' => 1500, 'dump' => $user));
} else {
return $this->render(
'registration/register.html.twig',
array('form' => $form->createView())
);
}
}
}
Add exit; after dump() or check the debug tab in profiler.
It is not visible because you have a redirect response.
If you are using the rest of the framework (as appears to be from the use of Controller), you'll find it linked from the debug-toolbar. However, as you are doing a redirect, the page that you end up on isn't the same request as the dump was made.
If you go into the debug profiler, and click the 'Last 10' button (near the top-left), you will see the previous pages. It's very likely that the 2nd one down will have the 'dump' section linked from the left hand column, and you'll be able to check the output from there.
For my project, I need to redirect the user after registration. In order to achieve that, I created an EventListener as described below :
My Event Listener :
namespace UserBundle\EventListener;
use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class RegistrationConfirmListener implements EventSubscriberInterface
{
private $router;
public function __construct(UrlGeneratorInterface $router)
{
$this->router = $router;
}
/**
* {#inheritDoc}
*/
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_CONFIRM => 'onRegistrationConfirm'
);
}
public function onRegistrationConfirm(GetResponseUserEvent $event)
{
$url = $this->router->generate('standard_user_registration_success');
$event->setResponse(new RedirectResponse($url));
}
}
I registered it as a service in my service.yml :
services:
rs_user.registration_complet:
class: UserBundle\EventListener\RegistrationConfirmListener
arguments: [#router]
tags:
- { name: kernel.event_subscriber }
And I need to use it in my RegistrationController but I don't understand how to trigger it.
Here in my registerAction :
public function registerAction(Request $request)
{
$em = $this->get('doctrine.orm.entity_manager');
//Form creation based on my user entity
$user = new StandardUser();
$form = $this->createForm(RegistrationStandardUserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user ->setEnabled(true);
$em ->persist($user);
$em ->flush();
if ($user){
$dispatcher = $this->get('event_dispatcher');
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRM);
}
}
return $this->render('UserBundle:Registration:register.html.twig', array(
'form' => $form->createView()
));
}
I don't understand the Symfony2 documentation about the subject neither what I need to pass to the ->dispatch() function to trigger my event.
[EDIT]
I get this error when I register my user :
Type error: Argument 1 passed to
UserBundle\EventListener\RegistrationConfirmListener::onRegistrationConfirm()
must be an instance of UserBundle\EventListener\GetResponseUserEvent,
instance of Symfony\Component\EventDispatcher\Event given
500 Internal Server Error - FatalThrowableError
Your listener declares that it is subscribed to FOSUserEvents::REGISTRATION_CONFIRM but you are dispatching FOSUserEvents::REGISTRATION_COMPLETED. To trigger it you need to dispatch a FOSUserEvents::REGISTRATION_CONFIRM event
edit to match your edit, you need to pass the event in your services tags:
- { name: 'kernel.event_subscriber', event: 'fos_user.registration.confirm'}
I made this Controller to play around with Symfony 2.3
namespace AskThem\MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use AskThem\MainBundle\Entity\Task;
class DefaultController extends Controller {
private $context = array();
public function indexAction(Request $request) {
$task = new Task();
$form =
$this->createFormBuilder($task)
->add("task", "text")
->add("dueDate", "date")
->add("save", "submit")
->add("saveAndAdd", "submit")
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
// ... perform some action, such as saving the task to the database
$nextAction = $form->get('saveAndAdd')->isClicked()
? 'homepage'
: 'task_success';
return $this->redirect($this->generateUrl($nextAction));
}
$this->context["form"] = $form->createView();
return $this->render('AskThemMainBundle:Default:index.html.twig', $this->context);
}
public function successAction(Request $request) {
return new Response("Victory");
}
}
The form was working fine, so then I added a validation-yml file with some NotBlank rules to test if it would work, and indeed it did.
But when I deleted those rules (I even deleted the whole file) the form still kept presenting itself with the required attribute. How do I turn off the validation?