在最新的Symfony 2版本(使用FOSUserBundle和SonataUserBundle)上,我正在尝试获取当前用户,以便在我的新实体控制器中预先填写表格。
在mycontroller.yml上:
my_controller_new:
pattern: /new
defaults: { _controller: "MySiteBundle:MyController:new" }
在MyController.php上:
public function newAction()
{
$user = $this->getUser();
// ...
}
但是当我调用$this->getUser()
时,该方法返回null
。即使我已经登录(我可以访问/profile
并更新我的用户信息,没有任何问题)
然后我试着检查会话是否启动:
public function newAction()
{
var_dump($this->get('session')->isStarted());
// ...
}
返回false。这里怎么了?
public function newAction() {
$session = $this->getRequest()->getSession(); // Get started session
if(!$session instanceof Session)
$session = new Session(); // if there is no session, start it
$value = $session->getId(); // get session id
}