Symfony 2.7.3 cookie问题

时间:2015-08-12 08:30:15

标签: php symfony cookies

我对Symfony很新,我想建立一个网站,用户可以选择不同的显示板。所有电路板都在我的树枝模板中,如果cookie的值为0则隐藏。如果用户单击菜单,则cookie的值将更改为1,显示电路板。 但是,当我第一次单击菜单时,它不会改变任何东西,但第二次,它完美地工作。

这就是我设置cookie的方式:

$var = 0;
    $response = new Response();
    $response->headers->setCookie(new Cookie('stream', $var, time() + 3600));
    $response->send();

这就是我改变cookie值的方法:

    $response = new Response();
    $cookie = $this->getRequest()->cookies->get('stream');
    $var = 1;
    $response->headers->setCookie(new Cookie('stream', $var, time() + 3600));
    return $response;

编辑:这是我的控制器

 public function streamAction()
{

    $advert = $this->getAdvertEntity();
    $stream = $this->getStreamEntity();

    $cookie = $this->getRequest()->cookies->get('stream');
    if (!isset($cookie) || $cookie == 0) {
        $var = 1;
        $response->headers->setCookie(new Cookie('stream', $var, time() + 3600));
        $response->sendHeaders();
        return $this->redirectToRoute('stream', array(
            "adverts" => $advert,
            "liststream" => $stream
        ));
    }
    $content = $this->get('templating')->render('IVPlatformBundle:Advert:Advert.html.twig', array(
        "adverts" => $advert,
        "liststream" => $stream
    ));
    return new Response($content);
}

我真的不知道出了什么问题,所以任何帮助都会很好:)

由于

1 个答案:

答案 0 :(得分:1)

如果您是第一次访问该路线,则未在请求中设置Cookie,您会收到该响应。解决方案是在cookie更改时重定向到相同的路由:

$cookie = $this->getRequest()->cookies->get('stream');
    if (!isset($cookie) || $cookie == 0) {
        $var = 1;
        $response->headers->setCookie(new Cookie('stream', $var, time() + 3600));
        $response->sendHeaders();
        return $this->redirectToRoute('actual_route');
    }
    // Do other stuff if cookie set to 1.
    return $response;