Bob D bluntman
Bob D bluntman

Reputation: 3

Symfony 2.7.3 cookie issue

I am quite new to Symfony, and I want to set up a website were an user can select different board to display. All the board are in my twig template and are hidden if the value of the cookie is 0. If the user click on the menu, the value of the cookie will change to 1, displaying the board. However, when I click on the menu, the first time, it does not change anything, but the second time, it work perfectly.

This is how I set up my cookie:

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

And this is how I change the value of the cookie:

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

Edit: Here is my controller

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

I really don't know what is wrong, so any help will be nice :)

Thanks

Upvotes: 0

Views: 845

Answers (1)

malcolm
malcolm

Reputation: 5542

If you first time visit the route, cookie is not set in request, you receive it in response. Solution is to make redirect to the same route if cookie changed:

$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;

Upvotes: 1

Related Questions