Answer the question
In order to leave comments, you need to log in
How to manage cookies in Yii2?
Help with advice! What am I doing wrong?
There is a user who belongs to two cabinets. It is necessary to organize a quick change of cabinets, since creating separate logins for 1 user is not a hunt.
Here is a part of the code, during authorization, the saved cabinet is checked in the SiteController.php controller
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
$rows = (new \yii\db\Query())
->select(['kabinet_id'])
->from('users_filtr')
->where(['IP' =>Yii::$app->request->userIP])
->andWhere(['user_id'=>Yii::$app->user->id])
->one();
$cookies = Yii::$app->response->cookies;
if (empty($cookies['kabinet']) && $rows){
$userid = Yii::$app->user->id;
//получаем список кабинетов пользователя
$kabinet= User::findOne($userid)->kabinet;
$i=0;
foreach ($kabinet as $litem){
//если кабинетов много и куки пусты, то задаем 1-ый по списку
if($i==0){
$kabinet_id=$litem->id;
}
$i++;
}
$cookies->add(new \yii\web\Cookie([
'name' => 'kabinet',
'value' =>$kabinet_id,
]));
Yii::$app->db->createCommand()->insert('users_filtr', [
'IP' =>Yii::$app->request->userIP,
'kabinet_id' =>$kabinet_id,
])->execute();
}
return $this->goHome();
}
и актион для изменения куков, так же находиться на SiteController
public function actionGetcoockeikab(){
if(Yii::$app->request->isAjax){
$kabinet_id=Yii::$app->request->post('kabinet_id');
$ip=Yii::$app->request->userIP;
$user_id=Yii::$app->user->id;
Yii::$app->db->createCommand("UPDATE users_filtr SET kabinet_id='$kabinet_id' WHERE IP='$ip' AND user_id='$user_id' ")->execute();
$coockie=Yii::$app->response->cookies;
//Вот тут я вообще правильно ли делаю для перезаписи куков?
$coockie->remove('kabinet');
$coockie->add(new \yii\web\Cookie([
'name' => 'kabinet',
'value' =>$kabinet_id,
]));
return Apu::findOne($kabinet_id)->name_lu;
}
}
$('#form_kab').children('ul').find('li').click(function () {
var kab_id=$(this).attr('id');
$.ajax({
url: '/site/getcoockekab',
type: 'post',
dataType: 'html',
data:{
kabinet:kab_id
},
success:function (data) {
location.reload();
}
});
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question