E
E
edik892016-05-13 13:01:05
Yii
edik89, 2016-05-13 13:01:05

How to send cookie to browser using yii2?

Hello!
The question is the following. There is a method:

public function actionTest() {
    	$cookie = new \yii\web\Cookie([
            'name' => 'test',
            'value' => 'test cookie value',
            //'expire' => time() + 3600 * 24 * 1000,
        ]);

        Yii::$app->response->cookies->add($cookie);
    }

In this case everything works fine and I can see the test cookie in the browser.
If the method renders any view, for example:
public function actionTest() {
    	$cookie = new \yii\web\Cookie([
            'name' => 'monster',
            'value' => 'test cookie value',
            //'expire' => time() + 3600 * 24 * 1000,
        ]);

        Yii::$app->response->cookies->add($cookie);

        return $this->render('index');
    }

, the cookie is not set. That is, the point is in the render method. How to do so. so that in one action it was possible to set a cookie and render a view?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2016-05-13
@edik89

public function actionTest() {
    	$cookie = new \yii\web\Cookie([
            'name' => 'monster',
            'value' => 'test cookie value',
            //'expire' => time() + 3600 * 24 * 1000,
        ]);
        Yii::$app->response->cookies->add($cookie);

        return $this->render('index');
    }

this code is correct and should work, if it doesn't work then you are doing something wrong in the view, show its code...

E
edik89, 2016-05-17
@edik89

Yes, the problem was that the following code was lost somewhere in the template:
<?php $this->beginPage() ?>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question