Symfony - how to lowercase a form field? - symfony

I'm a beginner to using Symfony 3.4 and I would like to change a form field to lower case but I don't know how or where :(
In my buildForm with maybe a constraint or in my Controller but I can't target the form field ?
I tried in Twig:
<div>{{ form_widget(form.name)|lower }}</div>
I tried in Controller:
$form->get('name')->setData(strtolower($form->get('name')));
I tried in buildForm:
$builder->add('name', TextType::class, ['attr' => array( 'class' => 'text-lowercase' ))
If you need to see my Controller :
public function registerAction(Request $request)
{
/** #var $formFactory FactoryInterface */
$formFactory = $this->get('fos_user.registration.form.factory');
/** #var $userManager UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
/** #var $dispatcher EventDispatcherInterface */
$dispatcher = $this->get('event_dispatcher');
$user = new User();
$user->setEnabled(true);
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
$form = $formFactory->createForm();
$user->setUsername("null");
$user->setPassword("null");
$user->setPlainPassword("null");
$form->setData($user);
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
$user->setPassword(strtolower($form["name"]->getData(). $form["firstname"]->getData()));
$user->setPlainPassword(strtolower($form["name"]->getData(). $form["firstname"]->getData()));
$user->setUsername(strtolower($form["name"]->getData().
$form["firstname"]->getData()));
if($form["roles"]->getData() == 'ROLE_ADMIN')
{
$user->addRole('ROLE_ADMIN');
}
else
{
$user->addRole('ROLE_USER');
}
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
$userManager->updateUser($user);
/*****************************************************
* Add new functionality (e.g. log the registration) *
*****************************************************/
$this->container->get('logger')->info(
sprintf("New user registration: %s", $user)
);
if (null === $response = $event->getResponse()) {
$url = $this->generateUrl('fos_user_registration_register');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_FAILURE, $event);
if (null !== $response = $event->getResponse()) {
return $response;
}
}
return $this->render('#FOSUser/Registration/register.html.twig', array(
'form' => $form->createView(),
));
}
Thank you for any help !

If you are using bootstrap following code should be work:
$builder->add('name', TextType::class, ['attr' => array( 'class' => 'text-lowercase' ))

Related

redirect to login after register

when i enabled confirmation email in register fosuserbundle it redirect automaticly to page login and in profilet i have status 302 for routing fos_user_registration_check_email also user is not created and when i disabled confirmation email i haven't any error and user is created.
controller:
/**
* #Route("/register", name="register_babysitter")
*/
public function registerAction(Request $request)
{
/** #var $dispatcher EventDispatcherInterface */
$dispatcher = $this->get('event_dispatcher');
$user= new BabySitter();
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
$form= $this->createForm(BabySitterType::class, $user);
$form->setData($user);
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
$this->uploadDocument->upload($user->getPicture(), $this->getParameter('pictures_directory'));
$this->uploadDocument->upload($user->getCriminalRecord(), $this->getParameter('criminalRecord_director_babySitter'));
$this->uploadDocument->uploadIdCard($user->getIdCards(), $user,$this->getParameter('idCard_directory'));
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
if (null === $response = $event->getResponse()) {
$url = $this->generateUrl('fos_user_registration_confirmed');
$response = new RedirectResponse($url);
}
$response = $event->getResponse();
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_FAILURE, $event);
if (null !== $response = $event->getResponse()) {
return $response;
}
}
return $this->render('AppBundle:BabySitter:register.html.twig', array(
'form' => $form->createView()
));
}
config:
fos_user:
db_driver: orm
firewall_name: main
user_class: AppBundle\Entity\User
service:
mailer: fos_user.mailer.twig_swift
from_email:
address: "test#gmail.com"
sender_name: "test#gmail.com"
registration:
confirmation:
enabled: true
help me please and thanks
You can also implements the method confirmAction() and confirmedAction() and to create your own logic:
/**
* Receive the confirmation token from user email provider, login the user.
*
*
* #Route("/register/confirm/{token}", name="registration_confirm")
*
* #param Request $request
* #param string $token
*
* #return Response
*/
public function confirmAction(Request $request, $token)
{
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->findUserByConfirmationToken($token);
if (null === $user) {
throw new NotFoundHttpException(sprintf('The user with confirmation token "%s" does not exist', $token));
}
/** #var $dispatcher EventDispatcherInterface */
$dispatcher = $this->get('event_dispatcher');
$user->setConfirmationToken(null);
$user->setEnabled(true);
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRM, $event);
$userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
$url = $this->generateUrl('register_confirmed');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRMED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
/**
* Tell the user his account is now confirmed.
*
* #Route("/register/confirmed", name="register_confirmed")
*/
public function confirmedAction()
{
$user = $this->getUser();
if (!is_object($user) || !$user instanceof UserInterface) {
throw new AccessDeniedException('This user does not have access to this section.');
}
return $this->render('frontend/register_success.html.twig', array(
'user' => $user,
'targetUrl' => $this->getTargetUrlFromSession(),
));
}
Remember also in the template of the email to use the route registration_confirm.
Basically, in these two actions, you could define the route you want to redirect once your user is register.

Submitting symfony register controller fosuserbundle does not work

I tried to follow this tutorial to override default controller of fos user bundle [Overriding Default FOSUserBundle Controllers][1]
And i can change controller but when I try to submit button it doesn't work:
<?php
// src/AppBundle/Controller/RegistrationController.php
namespace AppBundle\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use FOS\UserBundle\Controller\RegistrationController as BaseController;
use Symfony\Component\HttpFoundation\Request;
class RegistrationController extends BaseController
{
public function registerAction(Request $request)
{
/** #var $formFactory FactoryInterface */
$formFactory = $this->get('fos_user.registration.form.factory');
/** #var $userManager UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
/** #var $dispatcher EventDispatcherInterface */
$dispatcher = $this->get('event_dispatcher');
$user = $userManager->createUser();
$user->setEnabled(true);
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);
var_dump('prova');
if (null !== $event->getResponse()) {
return $event->getResponse();
}
$form = $this->createForm(RegistrationType::class, $user, [
'method' => 'POST',
]);
//$form = $formFactory->createForm();
//$form->setData($user);
$form->handleRequest($request);
if ($form->isSubmitted()) {
var_dump($form);
if ($form->isValid()) {
var_dump($form);
}
}
return $this->render('#FOSUser/Registration/register.html.twig', array(
'form' => $form->createView(),
));
}
}
The var_dump before the submit work but the var_dump inside
if ($form->isSubmitted()) {
if ($form->isValid()) {
doesn't work . I believe that submit logic is in another code but i don't understand how I can change it.
I don't understand how it's possible. Please help me ?
You don't set a formType to your form, so he have nothing to handle.
Here is a simple example :
$form = $this->createForm(YourFormType::class, $user, [
'method' => 'POST',
]);
Good luck ! :)

How to write unit test in symfony3

I want to know how to write standard unit test code for the below controller. I believe PHPUNIT is installed by default in symfony3 but I'm not sure how to execute it as well. Can someone guide me how to write testcontroller and execution command for symfony3 as well.
class RegistrationController extends Controller
{
/**
* #Route("/register", name="user_registration")
* #Security("has_role('ROLE_SUPER_ADMIN')")
*/
public function userAction(Request $request)
{
$user = new User();
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($request->isMethod('POST') && $form->isValid()) {
$password = $this->get('security.password_encoder')
->encodePassword($user, $user->getPlainPassword());
$user->setPassword($password);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$this->get('app.mailer')->sendUserCredentials($user);
$this->addFlash('notice', 'An account is created');
}
return $this->render('masteradmin/account/addUser.html.twig',
array('form' => $form->createView())
);
}
/**
* #Route(
* "/user/edit/{id}",
* requirements={"id" = "\d+"},
* name="user_edit"
* )
*/
public function editUserAction(User $user, Request $request)
{
if (!$this->get('security.authorization_checker')->isGranted('ROLE_SUPER_ADMIN')) {
throw new AccessDeniedException();
}
$em = $this->getDoctrine()->getManager();
$id = $request->attributes->get('id');
if (!$user = $em->getRepository('AppBundle:User')->findOneById($id)) {
throw new NotFoundHttpException('user details not found.');
}
$form = $this->createForm(UserType::class, $user)
->remove('plainPassword');
$form->handleRequest($request);
$data = $form->getData();
if ($form->isValid()) {
$em->persist($user);
$em->flush();
$this->addFlash('notice', 'Account information is updated');
return $this->redirectToRoute('user_list');
}
return $this->render(
'masteradmin/account/editUser.html.twig', ['form' => $form->createView()]
);
}

Insert foreign key in Symfony2 in OneToMany relation

I have a problem with adding data to the db. I have two entities InternalDocument and InternalDocumentProduct in OneToMany relation.
In InternalDocument:
/**
* #ORM\OneToMany(targetEntity="InternalDocumentProduct", mappedBy="document", cascade={"all"})
**/
protected $products;
In InternalDocumentProduct
/**
* #ORM\ManyToOne(targetEntity="InternalDocument", inversedBy="products")
* #ORM\JoinColumn(name="document_id", referencedColumnName="id")
* */
protected $document;
When I create new InternalDocument I need to insert InternalDocumentProduct too. But When i call persist() method, InternalDocumentProduct is saved without document_id field. It's null. This is my createForm() method in InternalDocumentController:
/**
* Creates a new InternalDocument entity.
*
*/
public function createAction(Request $request)
{
$entity = new InternalDocument();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
if ($form->isValid()) {
$em->persist($entity);
$em->flush();
$em = $this->getDoctrine()->getManager();
foreach($entity->getProducts() as $p) {
$em->persist($p);
}
$em->flush();
return $this->redirect($this->generateUrl('acme_warehouse_documents'));
}
return $this->render('AcmeWarehouseBundle:InternalDocument:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
Can anyone help me?
EDIT:
I resolve this problem. I modified createAction method:
/**
* Creates a new InternalDocument entity.
*
*/
public function createAction(Request $request)
{
$entity = new InternalDocument();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
if ($form->isValid()) {
foreach($entity->getProducts() as $p) {
$p->setDocument($entity);
}
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('acme_warehouse_documents'));
}
return $this->render('AcmeWarehouseBundle:InternalDocument:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}

FOSUserBundle override action of a controller

I'm trying to override the editAction in ProfileController.php but it's doesn't work. I can override template and form with success but not the actions of controllers.
app/config.yml
# FOS UserBundle Configuration
fos_user:
db_driver: orm
firewall_name: main
user_class: Intranet\UserBundle\Entity\User
registration:
form:
type: intranet_user_registration
profile:
form:
type: intranet_user_profile
old src/Intranet/UserBundle/Controller/ProfileController.php
<?php
namespace Intranet\UserBundle\Controller;
use FOS\UserBundle\Controller\ProfileController as BaseController;
class ProfileController extends BaseController
{
/**
* Edit the user
*/
public function editAction(Request $request)
{
var_dump($request) die(); // just for the test
}
}
new src/Intranet/UserBundle/Controller/ProfileController.php
<?php
namespace Intranet\UserBundle\Controller;
use FOS\UserBundle\Controller\ProfileController as BaseController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
class ProfileController extends BaseController
{
public function editAction(Request $request)
{
$user = $this->container->get('security.context')->getToken()->getUser();
if (!is_object($user) || !$user instanceof UserInterface) {
throw new AccessDeniedException('This user does not have access to this section.');
}
/** #var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
$dispatcher = $this->container->get('event_dispatcher');
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
/** #var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
$formFactory = $this->container->get('fos_user.profile.form.factory');
$form = $formFactory->createForm();
$form->setData($user);
if ('POST' === $request->getMethod()) {
$form->bind($request);
if ($form->isValid()) {
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->container->get('fos_user.user_manager');
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);
$userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
$url = $this->container->get('router')->generate('fos_user_profile_show');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
}
return $this->container->get('templating')->renderResponse(
'FOSUserBundle:Profile:edit.html.'.$this->container->getParameter('fos_user.template.engine'),
array('form' => $form->createView())
);
}
}
src/Intranet/UserBundle/IntranetUserBundle.php
<?php
namespace Intranet\UserBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class IntranetUserBundle extends Bundle
{
public function getParent()
{
return 'FOSUserBundle';
}
}
No error message, SF2 ignore my override :/
Ok I found, the controller need the same use of his parent
Last version of ProfileController :
namespace Intranet\UserBundle\Controller;
/* ALL USE IS REQUIRED !!!! */
use FOS\UserBundle\Controller\ProfileController as BaseController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
class ProfileController extends BaseController
{
public function editAction(Request $request)
{
$user = $this->container->get('security.context')->getToken()->getUser();
if (!is_object($user) || !$user instanceof UserInterface) {
throw new AccessDeniedException('This user does not have access to this section.');
}
/** #var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
$dispatcher = $this->container->get('event_dispatcher');
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
/** #var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
$formFactory = $this->container->get('fos_user.profile.form.factory');
$form = $formFactory->createForm();
$form->setData($user);
if ('POST' === $request->getMethod()) {
$form->bind($request);
if ($form->isValid()) {
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->container->get('fos_user.user_manager');
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);
$userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
$url = $this->container->get('router')->generate('fos_user_profile_show');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
}
return $this->container->get('templating')->renderResponse(
'FOSUserBundle:Profile:edit.html.'.$this->container->getParameter('fos_user.template.engine'),
array('form' => $form->createView())
);
}
}

Resources