2012-07-16 63 views
0

我在添加評論到我網站上的照片時遇到問題。在評論表中,我有: id,user_id,photo_id,content,created,modified,erasedCakePHP爲照片添加評論

鑑於我創建:

echo $this->Form->create('Comment'); 
echo $this->Form->input('title'); 
echo $this->Form->input('content'); 
echo $this->Form->input($this->Session->read('User.id'), array('type'=>'hidden')); 
echo $this->Form->input($photo['Photo']['id'], array('type'=>'hidden')); 
echo $this->Form->end('Add comment'); 

我不知道這是否是正確的方法。蛋糕會如何知道2個隱藏值是user_idphoto_id

Thx for advices。

+0

如果你做得正確並且模型關聯設置正確,Cake知道user_id和photo_id是隱藏的,因爲它們是外鍵。然而,你正在使用'FormHelper :: input()',所以Cake不知道這兩個輸入應該是什麼。 – 2012-07-16 09:26:24

回答

3

當提交數據時(因此用戶不能作爲其他用戶發佈),您將不得不在控制器中填充用戶標識。您可以使用$this->Auth->user('id');(假設您使用內置的Auth組件)獲取用戶ID。至於照片ID,您顯然有這個地方,因爲你正在加載照片,你只需要在保存之前將這些數據傳遞到$this->request->data

一個簡單的CakePHP 2的方法是,像這樣:

public function viewPhoto($photoId) { //$photoId comes from your routes or something 

    if($this->request->is('post')) { 
     $this->request->data['Comment']['user_id'] = $this->Auth->user('id'); 
     $this->request->data['Comment']['photo_id'] = $photoId; 
     $this->Photo->Comment->save($this->request->data); 
    } 

} 

這個結構對你稍有不同,這取決於你的控制器/模型建立。

+3

最好不要向窗體添加隱藏值(尤其是沒有安全組件激活),而是在save()調用之前在控制器中添加這些值。 – mark 2012-07-16 09:32:31

+0

mark你能舉個例子嗎? – Chris 2012-07-16 10:41:16

+3

@mark這正是我在做什麼?注意'('post')' – Dunhamzzz 2012-07-16 11:27:28