CakePHP3でデータ保存前に特定の値をセットする
の編集
https://yassu.jp/pukiwiki/index.php?CakePHP3%A4%C7%A5%C7%A1%BC%A5%BF%CA%DD%C2%B8%C1%B0%A4%CB%C6%C3%C4%EA%A4%CE%C3%CD%A4%F2%A5%BB%A5%C3%A5%C8%A4%B9%A4%EB
[
トップ
] [
編集
|
差分
|
バックアップ
|
添付
|
リロード
] [
新規
|
一覧
|
検索
|
最終更新
|
ヘルプ
]
-- 雛形とするページ --
(no template pages)
[[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']); }
タイムスタンプを変更しない
[[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']); }
テキスト整形のルールを表示する