2015-10-04 112 views
0

我有一個頁面,我可以修改用戶詳細信息(用戶名,名字,頭像...)。 我在我的導航欄中有一個關於當前登錄用戶信息的元素。事情是我無法弄清楚如何在數據修改後立即刷新會話。CakePHP 3刷新會話數據

UsersController

public function edit($id = null) 
{ 
    if (!$id) { 
     throw new NotFoundException(__('Invalid user')); 
    } 

    $user = $this->Users->get($id); 
    if ($this->request->is(['post', 'put'])) { 
     $this->Users->patchEntity($user, $this->request->data); 
     if ($this->Users->save($user)) { 

      //REFRESH SESSION ????\\ 
      $this->request->session()->write('Auth.User', $user); 
      //\\ 

      $this->Flash->success(__('User has been updated.')); 
      return $this->redirect(['action' => 'edit/' . $id]); 
     } 
     $this->Flash->error(__('Unable to update User details.')); 
    } 

    $this->set(compact('user')); 
} 

回答

7

只需更新它,你會在洛時,即使用AuthComponent::setUser()設置同樣的方式。

此外,只有在編輯過的用戶實際上是當前登錄的用戶的情況下,您也可以這樣做。並且您希望以與Auth組件相同的格式設置數據,即(現在),作爲一個數組,並出於安全的目的,沒有密碼。

,它假定名爲id單個列的主鍵,並將其命名password

if ($this->Auth->user('id') === $user->id) { 
    $data = $user->toArray(); 
    unset($data['password']); 

    $this->Auth->setUser($data); 
} 

參見

+2

'unset($ data ['password'])'不應該是必須的,因爲它應該位於實體內部的隱藏屬性中。 –

+0

@StefanD。在一個理想的世界中,無論烘焙功能在一個月前是否被破解(烘烤1.1.4),人們甚至可能不會使用烘焙和/或使用「token」,「password」以外的列和'passwd'(這是什麼烘烤檢測),所以我說它仍然值得一提的是,人們應該留意這一點。 – ndm