How to write unit test in symfony3 - phpunit

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()]
);
}

Related

Binding entities to query parameters only allowed for entities have an identifier

I am using a Symfony 4 project, and I want to change the user password, so I created a method in my repository and called it to the controller, but this error it diplay to me,
Binding entities to query parameters only allowed for entities that have an identifier.
Repository
public function updateU($password,$email): ?Utilisateur
{
$dql = <<<DQL
SELECT u
FROM App\Entity\Utilisateur u
WHERE u.email = :email
AND u.password = :password
DQL;
return $this->getEntityManager()->createQuery($dql)
->setParameters(['email' => $email, 'password' => $password])
->getSingleScalarResult();
}
Controller
/**
* #Route("/Reset", name="Reset")
* Method({"GET"})
*/
public function New(
Request $request,
UtilisateurRepository $URe,
UserPasswordEncoderInterface $userPasswordEncoder,
EntityManagerInterface $entityManager,
MailerInterface $mailer
) {
$o = '';
$Varmail = $_GET['email'];
$user = new Utilisateur($o);
$form = $this->createFormBuilder($user)
->add('password', PasswordType::class)
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$to = $Varmail;
$sujet = 'Password Changed';
$Message = "Bonjour $Varmail Votre email est changé !";
$pass = $user->setPassword(
$userPasswordEncoder->encodePassword(
$user,
$form->get('password')->getData()
)
);
$URe->updateU($pass, $Varmail);
$Mai = new MailerController();
$Mai->sendEmail($mailer, $to, $sujet, $Message);
}
return $this->render('modifier_mdp/index.html.twig', [
'form' => $form->createView(),
]);
}
How can i solve it , And Thanks
In your updateU method, you are making a request to get, not update the data. It's better to use the ObjectManager to save the data, since you still have a updated instance of the Utilisateur object in the $user variable.
$user = $this->getDoctrine()->getManager()->getRepository(Event::class)->findOneBy(['email'=>$Varmail]);
$form = $this->createFormBuilder($user)->add('password', PasswordType::class)->getForm();
if ($form->isSubmitted() && $form->isValid()) {
// ...
$user->setPassword(
$userPasswordEncoder->encodePassword(
$user,
$form->get('password')->getData()
)
);
// save Utilisateur with new password
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
}

Symfony - how to lowercase a form field?

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' ))

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(),
));
}

how to remove unable to find entity error?

i make an update function of controller but when i insert values in fields and the submit the exception return,i make an update function of controller but when i insert values in fields and the submit the exception return,
"Unable to find Sections entity"
here is my controller code:
public function updateAction(Request $request, $id)
{
if(isset($_SESSION['id'])) {
$proposalid=$_SESSION['id'];
}
$user = $this->get('security.context')->getToken()->getUser();
$userId = $user->getId();
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ProposalsProposalsBundle:Sections')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Sections entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createForm(new SectionsType(), $entity);
$editForm->bind($request);
$sectioncounter = $request->request->get('sectioncounter');
$date= new \DateTime();
$query = $em->createQuery("Delete from ProposalsProposalsBundle:Sections s where s.proposalID='".$proposalid."'");
$ids = $query->getResult();
if($request->isXmlHttpRequest()) {
$response = new Response();
for($i=0; $i<$sectioncounter; $i++){
$sectionname = $_POST['sectionName'.$i];
$description=$_POST['description'.$i];
$entity->setSectionName($sectionname);
$entity->setDescription($description);
$entity->setProposalID($proposalid);
$entity->setCreatedBy($userId);
$entity->setUpdatedBy($userId);
$entity->setCreatedDatetime($date);
$entity->setUpdatedDatetime($date);
$em->persist($entity);
$em->flush();
$em->clear();
}
return $response;
}
return $this->render('ProposalsProposalsBundle:Sections:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
how to remove this exception?
Symfony2 has its own session handler. To set a session variable:
$session = $this->getRequest()->getSession();
$session->set('member', $member);
To get a session variable:
$session = $this->getRequest()->getSession();
$member = $session->get('member');

Symfony2 persist correlated objects

This my issue:
Entity AddressBook 1-N Entity Number
The controller displays the edit form with AddressBook and its number, but when I save the form, I get this error:
Fatal error: Call to a member function setTipo() on a non-object
Strangely, however, the data is saved correctly
This my code:
/**
* Modifica dati Anagrafica
* #Route("/contatto/{id}/modifica", name="_anagrafica_modifica")
* #Template()
*/
public function modificaAction($id)
{
$em = $this->getDoctrine()->getManager();
$anagrafica = $em->getRepository('MercurioInterfaceBundle:Anagrafica')->find($id);
if (!$anagrafica) {
throw $this->createNotFoundException('No anagrafica found for id '.$id);
}
$form = $this->createForm(new \Mercurio\InterfaceBundle\Form\Anagrafica\FormAnagrafica(), $anagrafica);
$request = $this->getRequest();
if ($request->getMethod() == 'POST')
{
$form->bind($request);
if ($form->isValid())
{
$chiave = $request->request->get('anagrafica');
$em = $this->getDoctrine()->getManager();
$anagrafica = $em->getRepository('MercurioInterfaceBundle:Anagrafica')->find($id);
$anagrafica->setNominativo($chiave['nominativo']);
$anagrafica->setIndirizzo($chiave['indirizzo']);
$anagrafica->setCap($chiave['cap']);
$anagrafica->setCitta($chiave['citta']);
$anagrafica->setNote($chiave['note']);
$em->flush();
$dettaglio = $em->getRepository('MercurioInterfaceBundle:AnagDettaglio')->findBy(array('anagrafica_id' => $id,));
foreach ($chiave['anag_dettagli'] as $d)
{
$dettaglio->setTipo($d['tipo']);
$dettaglio->setValore($d['valore']);
$dettaglio->setRiferimento($d['riferimento']);
}
$em->flush();
return $this->redirect($this->generateUrl('_anagrafica_contatto', array('id' => $id)));
}
}
return array(
'form' => $form->createView(),
'id' => $id
);
}
Solved:
$form = $this->createForm(new \Mercurio\InterfaceBundle\Form\Anagrafica\FormAnagrafica(),$anagrafica);
if ($request->isMethod('POST')){
$form->bind($request);
if ($form->isValid()) {
$em->persist($anagrafica);
$em->flush();
return $this->redirect(....)
}
}

Resources