Getting session ID with $session->getId() returns an empty result in Symfony2
Asked Answered
S

2

5

I want to getting session ID to store it in the database (because I store shopping carts in my database). Thereby, I want to get session ID, with this method:

$session = $this->get('session');
$carts->setSessionId($session->getId());

But this method returns an empty result. It's really weird because if I send this ID in my view with, for exemple:

'session' => $session->getId(),

It works... It's really strangely ; have I make an error in my code?

getSessionId() and setSessionId() functions:

/**
 * Set sessionId
 *
 * @param string $sessionId
 * @return Carts
 */
public function setSessionId($sessionId)
{
    $this->sessionId = $sessionId;

    return $this;
}

/**
 * Get sessionId
 *
 * @return string 
 */
public function getSessionId()
{
    return $this->sessionId;
}

Thank you per advance!

Soelch answered 25/5, 2013 at 20:30 Comment(10)
what is $carts in your example ? a collection, a single object?Bromism
$carts is an entity (to store carts in database)Soelch
what do you mean this method returns an empty result? after calling $carts->setSessionId($sesson->getId()) ... $carts->getSessionId() does not return the id ? if yes please provide a gist /pastebin with those 2 methods or post them hereBromism
after calling $carts->setSessionId($sesson->getId()), $carts->getSessionId() no return ID (I did $a = $carts->getSessionId() and I sent this variable to my view)Soelch
then please put your getSessionId and setSessionId methods into the question so we can inspect them.Bromism
it's done, but please confirm that I've put is what you've asked (I'm still pretty novice on Symfony2)Soelch
Yes that's what i wanted to see but i don't see anything wrong here ...do you have a protected/private property sessionId in your entity ? By the way .. method arguments are under_score by convention in symfony2Bromism
It's not me but the doctrine generator who not use the under_score convention. :-° $sessionId is private, so I just tried to put it in protected and public but neither works.Soelch
what is the return value of $session->isStarted() in your controller?Bromism
So I added $session->start(); and no it works! Really thank you!Soelch
J
7

Please make sure your session has been started otherwise Session::getId() returns am empty string (''). See Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage

$session = $this->get('session');
$session->start();
$carts->setSessionId( $session->getId() );
Jeweller answered 25/5, 2013 at 23:54 Comment(1)
Really thank you, although I'm disgusted to have had a so small errorSoelch
Z
1

The getId() method returns an empty string if the session has not been started yet. When starting the session manually, don't forget to check if the session hasn't been started already.

if(!$session->isStarted()) {
    $session->start();
}
Zel answered 16/5 at 9:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.