###前提・実現したいこと
not null制約が複数あるUsersテーブルに対し、
UsersのFormを作成し、そこで入力した項目をDBに登録しようとしております。
その際、not null制約がある項目が空だった場合にデフォルト値を設定してDBに登録したいと考えています。
パッと思いついたのが、UsersControllerでFormのPOSTを取得した後、
saveする前にnot null制約の項目を確認し、空ならデフォルト値を設定すればと思ったのですが、
何かTableやEntityで項目のデフォルト値を設定する機能はあったりしますでしょうか?
###Usersテーブル構成
項目名 | not null制約 |
---|---|
id | - |
氏名 | ◯ |
メアド | ◯ |
電話番号 | ◯ |
###UsersController.php
php
1public function add() 2{ 3 $user = $this->Users->newEntity(); 4 if ($this->request->is('post')) { 5 // ここで空かチェックするイメージ、not null制約の項目分続く 6 if (!isset($user->氏名)) { $user->氏名 = '山田 太郎'; } 7 if (!isset($user->メアド)) { $user->メアド = 'test@test.jp'; } 8 if (!isset($user->電話番号)) { $user->電話番号 = '000-0000-0000'; } 9 $user = $this->Users->patchEntity($user, $this->request->getData()); 10 if ($this->Users->save($user, ['validate' => 'registration'])) { 11 $this->Flash->success(__('You are now registered.')); 12 } else { 13 $this->Flash->error(__('There were some problems.')); 14 } 15 } 16 $this->set('user', $user); 17}
###補足情報(言語/FW/ツール等のバージョンなど)
CakePHP3.4
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2017/03/29 01:22