2011-11-10 54 views
0

我在加入車票不管是誰登錄的問題,CakePHP的1.3這條線工作完全正常:$this->data['Ticket']['user_id'] = $this->Auth->user();下面是完整的附加動作:如何在cakephp 2.0中登錄的用戶下添加門票?

public function add() { 
    if ($this->request->is('post')) { 
    $this->Ticket->create(); 
    $this->data['Ticket']['user_id'] = $this->Auth->user(); 
    if ($this->Ticket->save($this->request->data)) { 
     $this->Session->setFlash(__('The ticket has been saved')); 
     $this->redirect(array('action' => 'index')); 
    } else { 
     $this->Session->setFlash(__('The ticket could not be saved. Please, try again.')); 
    } 
    } 

    $users = $this->Ticket->User->find('list'); 
    $this->set(compact('users')); 
} 

甚至沒有現在的代碼$this->Session->read('user_id');作品。那麼,兩者中的任何一個都添加了票據,但user_id是空白的。任何幫助將不勝感激。

+0

你調試的$這個 - 返回值> Auth->用戶()?我懷疑這實際上是一個id,但是是一組鍵。使用pr()來找出實際返回的內容。 – mark

+0

pr($ this-> Auth-> user('id'));返回1,這是登錄的當前用戶的正確ID。任何想法爲什麼ID未被保存? – Lyman

回答

2

$ this-> Auth-> user()返回一個數組,其中包含有關用戶的各種字段。我想你應該更換線路4:

$this->data['Ticket']['user_id'] = $this->Auth->user('id'); 

或者,你可以先分配的結果給一個變量,然後附加到票:

$user = $this->Auth->user(); 
$this->data['Ticket']['user_id'] = $user['User']['id']; 

編輯

我看到發生了什麼現在。您正在對對象進行編輯,然後保存請求數據...所以您的用戶ID永遠不會傳遞給保存。

試試這個:

public function add() { 
if ($this->request->is('post')) { 
    $this->Ticket->create(); 
    $data = $this->request->data; 
    $data['Ticket']['user_id'] = $this->Auth->user('id'); 
    if ($this->Ticket->save($data)) { 
     $this->Session->setFlash(__('The ticket has been saved')); 
     $this->redirect(array('action' => 'index')); 
    } else { 
     $this->Session->setFlash(__('The ticket could not be saved. Please, try again.')); 
    } 
} 

$users = $this->Ticket->User->find('list'); 
$this->set(compact('users')); 

}

+0

對不起,這實際上是我$ this-> data ['Ticket'] ['user_id'] = $ this-> Auth-> user('id');它不起作用。曾經與1.3一起工作。我忘了在我的代碼之後添加這兩行:$ users = $ this-> Ticket-> User-> find('list'); $ this-> set(compact('users')); – Lyman

+0

是否可以調試$ this-> Auth-> user('id');?的輸出它輸出什麼東西?事實上,你有沒有可能被認證? CakePHP用2.0改變了Auth模塊,所以問題可能在於你如何進行身份驗證而不是這個功能。 –

+0

pr($ this-> Auth-> user('id'));返回1,這是登錄的當前用戶的正確ID。任何想法爲什麼ID未被保存? – Lyman

相關問題