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

qmarlats picture qmarlats · May 25, 2013 · Viewed 11.3k times · Source

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!

Answer

Nicolai Fröhlich picture Nicolai Fröhlich · May 26, 2013

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