添加数据到cakephp3控制器中存储

时间:2015-04-22 23:15:31

标签: cakephp cakephp-3.0

我正在使用但我在cakephp 2.x的版本中遇到问题我可以在控制器中添加数据而我不需要从视图中发送它。

示例:

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和日期保存。 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 个答案:

答案 0 :(得分: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');