what is the role of handle request in symfony form - symfony

I'm using FormBuilderInterface , to create my form, so i find that i can validate my form using the function isvalid() , i have an issue with handleRequest($request) ,i did't understand what is the role of it.
here is my code :
function ajout2Action()
{
$client= new \Esprit\PiBundle\Entity\Client();
$formv= new \Esprit\PiBundle\Form\ClientType();
$form= $this->createForm($formv,$client);
$request = $this->get('request');
if($form->handleRequest($request)->isValid())
{
$em=$this->getDoctrine()->getManager();
$em->persist($client);
$em->flush();
}
thank you for your help .

straight from the docs its used to process the form data
it takes the POST’ed data from the previous request, processes it, and runs any validation (checks integrity of expected versus received data). it only does this for POST requests
read more

Related

CSRF Token from the controller

I have a controller getting a form posted.
public function myPostAction(Request $request)
{
$form = $this->createForm('my_form', $my_object);
$form->handleRequest($request);
#...
I can see my CSRF token posted as parameter
my_form[_token] => lH38HTm5P0Cv3TOc4-9xi2COx-cZ670mpJ_36gR8ccI
I simply need to read it
$form->get('_token')
This tells me
Child "_token" does not exist.
How can I get this token ?
Here is the workaround I'm going to use meanwhile:
$token = $request->get($form->getName())['_token'];
I also noticed by chance that the intention used to generate the token is the form name
$csrf = $this->get('form.csrf_provider');
$intention = $form->getName();
$token = $csrf->generateCsrfToken($intention);
Like #Pierre de LESPINAY said, it is possible to do it by retrieving Token Manager service.
This service can also be injected in your constructor like that :
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
...
public function __construct(CsrfTokenManagerInterface $tokenManager)
{
$this->tokenManager = $tokenManager;
}
And used later like previously demonstrated :
$token = $this->tokenManager->getToken('myformname')->getValue();
You can get it with:
$request->request->get('my_form[_token]');
If you didn't disable CSRF-protection it will be applied and validated automatically and you don't need to check it by self.

handleRequest($request) does not work for "GET" method in Symfony 2

I am a noobie in Symfony2. The handleRequest() function does not work for "GET" method whereas same code works fine for "POST".
public function addAction(Request $request){
$std = new Student();
$form = $this->createForm(new StudentForm, $std,
array( 'method'=>'GET'));
$form->handleRequest($request);
if($form->isSubmitted()){
$std= $form->getData();
$em= $this->getDoctrine()->getManager();
$em->persist($std);
$em->flush();
return $this->render('target.twig');
}
return $this->render('target twig',
array('newStdForm'=> $form->createView(),));
}
The above code is not working but if I change 'method':'GET' to 'method':'POST', then it works fine.
Specify the form's method in the StudentForm class's buildForm method. Therefore, handleRequest will be able to grab the GET parameters.
class StudentForm
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// ...
$builder->setMethod('GET');
}
}
I think it is because in POST requests, parameters are passed in the body of the HTTP request. And that handleRequest looks for those values inside the body of the request. But in a GET request, parameters are passed in the url directly. So I think that is why the handling doesn't work.
Usually we use GET to fetch a page or url and a POST to send info to server.
Are you sure your twig template is correct?
I faced this issue today.
Pierre Roland's answer is partially correct for the current version.
I checked the default "HttpFoundationRequestHandler" which is called in "handleRequest".
An explicit GET form will be considered "submitted" if:
the form has no name (if you use a form class for example).
the request query contains a parameter with the form's name.

Symfony 2 : access to form config and submitted data in PRE_SUBMIT event

I'm currently trying to access to my form config (and its options) in a PRE_SUBMIT FormEvent callback. However, when I'm doing that for example :
<?php
// This is my callback function for the PRE_SUBMIT event on a formtype element
public function preSubmit(FormEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
[...]
$myConfig = $form->get('my_form_element_child')->getConfig()->get('my_option');
?>
It raises an exception saying :
FormBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.
Actually, I can understand why : it is because the form data is going to be submitted.
However, it is a problem for me. Indeed, I need to find a way to create other fields in my form based on some config options, when the data is already entered by the user but before the data gets "handled" by the controller.
Any idea on how to do that?
Thank you !
Just replace
$myConfig = $form->get('my_form_element_child')->getConfig()->get('my_option');
to
$myConfig = $form->get('my_form_element_child')->getConfig()->getOption('my_option');

Backbone.js and Symfony2 form validation

I'm creating a single-page app with backbone.js and symfony2 and I need your opinion on one thing.
For example see this create user action. The request is sent by a backbone model (model.save), and I want to check values on the server side. My question is pretty simple, is it pertinent to use the symfony2 form validation to do this check ?
/**
*
* #Route("/user", defaults={"_format"="json"}, name="create_user")
* #Method({"POST"})
*/
public function createUserAction() {
$request = $this->get('request');
if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
$data = json_decode($request->getContent(), true);
$request->request->replace(is_array($data) ? $data : array());
}
$entity = new User();
$form = $this->createForm(new UserType(), $entity);
$form->bind($request);
...
}
If yes, how can I do that? Backbone sends JSON request body whereas bind method of Symfony2 form object only accepts URL encoding. I've already tried to use urlencode function without success.
Yes it is pertinent, you should always do server side validation. My question is where is your content variable coming from? I don't see it being assigned in the above code.
You could use FOSRestBundle. It has a "body listener", which will decode request body, and let you bind you form with a request that had a json body.
You can learn more about this feature in the FOSRestBundle documentation.

Ignore Password when user updates profile with FOSUserBundle

I am using FOSUserBundle and I am trying to create a page that allows a user to update their user profile. The problem I am facing is that my form does not require that the user reenter their password if they don't want to change/update their password. So when a user submits the form with an empty password the database will be updated with an empty string, and the user will not be able to log in.
How can I get my form to ignore updating the password field if it is not set? Below is the code I am using.
$user = $this->get('security.context')->getToken()->getUser();
//user form has email and repeating password fields
$userForm = $this->createForm(new UserFormType(), $user);
if ($request->getMethod() == 'POST') {
$userForm->bindRequest($request);
if($userForm->isValid()){
//this will be be empty string in the database if the user does not enter a password
$user->setPlainPassword($userForm->getData()->getPassword());
$em->flush();
}
}
I have tried a few things such as the following, but this is still empty because the bindRequest sets the empty password to the user
if($userForm->getData()->getPassword())
$user->setPlainPassword($userForm->getData()->getPassword());
I have also tried, but this results in a similar situation and causes an unneeded query
if($userForm->getData()->getPassword())
$user->setPlainPassword($userForm->getData()->getPassword());
else
$user->setPlainPassword($user->getPlainPassword());
Are there any elegant ways to handle this use case?
The problem is that you bind a form to a User Object before controls upon password.
Let's analyze your snippet of code.
Do the following
$user = $this->get('security.context')->getToken()->getUser();
will load an existing user into a User Object. Now you "build" a form with that data and if receive a post, you'll take the posted data into the previous object
$userForm = $this->createForm(new UserFormType(), $user);
if ($request->getMethod() == 'POST') {
$userForm->bindRequest($request);
So, onto bindRequest you have alredy lost previous password into the object (obviously not into database yet) if that was leave empty. Every control from now on is useless.
A solution in that case is to manually verify value of form's field directly into $request object before binding it to the underlying object.
You can do this with this simple snippet of code
$postedValues = $request->request->get('formName');
Now you have to verify that password value is filled
if($postedValues['plainPassword']) { ... }
where plainPassword I suppose to be the name of the field we're interesting in.
If you find that this field contain a value (else branch) you haven't to do anything.
Otherwise you have to retrieve original password from User Object and set it into $request corrisponding value.
(update) Otherwise you may retrieve password from User Object but since that password is stored with an hased valued, you can't put it into the $request object because it will suffer from hashing again.
What you could do - i suppose - is an array_pop directly into $request object and put away the field that messes all the things up (plainPassword)
Now that you had done those things, you can bind posted data to underlying object.
Another solution (maybe better because you move some business logic away from controller) is to use prePersist hook, but is more conceptually advanced. If you want to explore that solution, you can read this about form events
I think you should reconsider if this is in fact a good use case. Should users be able to edit other users passwords? At our institution we do not allow even the highest level admin to perform this task.
If a user needs their password changed we let them handle that themselves. If they have forgotten their password we allow them to retrieve it via email. If they need assistance with adjusting their email we allow our admins to assist users then. But all password updating and creation is done soley by the user.
I think it is great that FOSUserBundle makes it so difficult to do otherwise but if you must DonCallisto seems to have a good solution.
<?php
class User
{
public function setPassword($password)
{
if (false == empty($password)) {
$this->password = $password;
}
}
}
This will only update the password on the user if it isn't empty.
I have found a simple hack to get rid of the "Enter a password" form error.
Manualy set a dummy plainPassword in the user entity. After form validation just reset it before you flush the entity.
<?php
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('AppBundle:User')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Customer entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$postedValues = $request->request->get('appbundle_user');
/* HERE */ $entity->setPlainPassword('dummy'); // hack to avoid the "enter password" error
$editForm->handleRequest($request);
if ($editForm->isValid()) {
/* AND HERE */ $entity->setPlainPassword(''); // hack to avoid the "enter password" error
$em->flush();
return $this->redirect($this->generateUrl('customer_edit', array('id' => $id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}

Resources