Reputation: 1283
I am trying to use the session with Symfony.
In fact, I want to complete a form before login.
For this reason, I would like this scheme:
My controller:
public function customMadeAction(Request $request)
{
$session = $this->container->get('session');
$user = $this->container->get('security.context')->getToken()->getUser();
$CustomMade = new CustomMade();
$form = $this->createForm(new CustomMadeType(), $CustomMade);
$form->handleRequest($request);
if ($user === 'anon.') {
if($form->isValid()) {
# 1-Save in session
var_dump($CustomMade); #I have an array with all I need
$session->set('infos', $CustomMade); #It does not save my informations
# 2-Redirect to login/register
$securityContext = $this->container->get('security.context');
if (!$securityContext->isGranted('ROLE_USER')) {
throw new AccessDeniedException('Accès refusé');
} else {
# 3-Save in database
$em = $this->getDoctrine()->getManager();
$em->persist($CustomMade);
$em->flush();
}
}
}else{
if($form->isValid()) {
$CustomMade->setIdUser($user->getId());
$em = $this->getDoctrine()->getManager();
$em->persist($CustomMade);
$em->flush();
}
}
return $this->render('FrontBundle:Forms:customMade.html.twig', array(
'form' => $form->createView()
));
}
Upvotes: 2
Views: 2041
Reputation: 4835
The solution of Antoine is right,
You will have to serialize the object in order to be able to store it in the session.
The easiest way should be using the JMSSerializerBundle and decode your object as json:
$serializer = $this->container->get('serializer');
$jsonDecoded = $serializer->serialize($doctrineobject, 'json');
Btw. as stated in the comments this will serialize the whole doctrine structure connected to the entity.
However a toArray() function could be implemented into the entity in order to serialize an array structure only, but this approach becomes very complex when dealing with oneToOne oneToMany and manyToMany relationships
Upvotes: 2
Reputation: 549
I do not think you can store an object in a session. Here are a few solutions :
As I see it, 1 is the fastest to implement, but it will be a pain to maintain if you later add fields to your entity. Solution 2 is better, but the deserialization is not so easy. I think solution 3 is the best, it is not that complicated to implement and will not cause any maintainance issue.
Upvotes: 3
Reputation: 163
If you want to save the data, save only the input data from the form (after validation) and not the entirely entity (with possibly a lot of... shit, unless that is what you want).
You can just set the object/array into the session and Symfony will take care of serializing and unserializing it for you
If this is the case, replace
$session->set('infos', $CustomMade);
by
$session->set('infos', $form->getData());
This way you'll be later simply do:
$data = $session->get('infos');
Upvotes: 2