[[CakePHP3めも]]

bakeで生成されるContollerのコードでは以下のようになると思います。

     public function add()
     {
         $user = $this->Users->newEntity();
         if ($this->request->is('post')) {
             $user = $this->User->patchEntity($user, $this->request->data);
             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']);
     }

save でデータが登録されますが、この時にフォームから送信された値以外にも登録したい場合も多々あります。~
その場合は patchEntity を当てる前にデータをセットします。

     public function add()
     {
         $user = $this->Users->newEntity();
         if ($this->request->is('post')) {
             $user->user_id = $this->Auth->user('id');    // 認証しているIDをセット
             $user = $this->User->patchEntity($user, $this->request->data);
             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']);
     }


トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS