2015-04-22 16 views
0

我正在使用但我在cakephp 2.x版本中遇到問題我可以在控制器中添加數據,並且我不需要從視圖中發送數據。添加數據以存儲在cakephp3控制器中

例如:

public function add() 
{ 
    $this->request->data['User']['id']=$this->Auth->user('id');//and save id 
    $this->request->data['User']['date']=$date('Y-m-d H:m:s');// and save date 
    if ($this->request->is('post')) {    
     if ($this->Users->save($user)) { 
      $this->Flash->success('The user has been saved.'); 
      return $this->redirect(['action' => 'index']); 
     } else { 
      $this->Flash->error('The user could not be saved. Please, try again.'); 
     } 
    } 
    $this->set(compact('user')); 
    $this->set('_serialize', ['user']); 
} 

在這裏,將數據添加到它已經收到,收到的信息和數據添加例如ID和日期。只是一個例子。如果我保存這些信息,則信息將以id和日期保存。身份證和日期不一定在視圖中。

現在我想在cakephp 3中做類似的事情,但不工作。

public function add() 
    { 
    $user = $this->Users->newEntity(); 
    $this->request->data['User']['id']=$this->Auth->user('id');//and don't save id 
    $this->request->data['User']['date']=$date('Y-m-d H:m:s');// and don't save date 
    if ($this->request->is('post')) { 

     $this->request['date'] = date("d-m-Y H:i:s"); 
     $user = $this->Users->patchEntity($user, $this->request->data); 
     debug($user); 
     if ($this->Users->save($user)) { 
      $this->Flash->success('The user has been saved.'); 
      return $this->redirect(['action' => 'index']); 
     } else { 
      $this->Flash->error('The user could not be saved. Please, try again.'); 
     } 
    } 
    $this->set(compact('user')); 
    $this->set('_serialize', ['user']); 
} 

搜索文檔,發現我解釋這更清楚

回答

1

老:

$this->request->data['User']['id']=$this->Auth->user('id');//and don't save id 
$this->request->data['User']['date']=$date('Y-m-d H:m:s');// and don't save date 

新:

$user = $this->Users->patchEntity($user, $this->request->data); 
$user->id=$this->Auth->user('id'); 
$user->date=$date('Y-m-d H:m:s'); 
0

因爲這是不工作的東西更多:

$this->request->data['User']['id'] 

現在

$this->request->data['id'] 

是搞亂前你應該瞎了,你應該read the migration guide,也許做CakePHP 3.0的博客教程瞭解差異,這將爲您節省大量時間。

+0

試試這個,但是當我想數據賦值給變量ID不起作用。 –

+0

您的問題或您的代碼沒有任何意義。優化你的問題。 – burzum

相關問題