CakePHPで少しつまずいたのでメモ。
以下のようなUsersテーブルに、nameカラムを追加しました。
User | type |
---|---|
id | ind |
varchar | |
password | varchar |
college | varchar |
created | datetime |
modified | datetime |
User | type |
---|---|
name | varchar |
そして、Userテーブルにデータを登録した時、ちゃんとname(ユーザー名)が保存されるか動作確認。
まず、user新規登録用のビューファイルに、nameの入力フォームを追加しました。
...
<?= $this->Form->create($user); ?>
<?= $this->Form->input('name'); ?> <!-- これを追加 -->
<?= $this->Form->input('email'); ?>
<?= $this->Form->input('password'); ?>
<?= $this->Form->input('college'); ?>
<?= $this->Form->button('登録'); ?>
<?= $this->Form->end(); ?>
...
値を入力して、いざ実行!
user一覧用のページにname(ユーザ名)を表示させると...あれ、何も表示されないぞ?
phpMyAdminを確認しても、nameカラムだけ空白になっている。
ビューファイルで <?= var_dump($_POST['name']); ?> を確認すると、きちんとPOSTされている。
ということはコントローラー側の処理の問題かな?と思い、
...
public function add()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$new = $this->Users->newEntity(); //確認のため追加
$user = $this->Users->patchEntity($user, $this->request->getData());
$data = $this->request->getData(); //確認のため追加
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
// return $this->redirect(['action' => 'index']);
// ↑ add.ctpでデバッグするためコメントアウト
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
$this->set(compact('user'));
$this->set(compact('new')); //確認のため追加
$this->set(compact('data')); //確認のため追加
}
...
として、ビューファイルで
<?= var_dump($new); ?>
と<?= var_dump($data); ?>
を確認すると、
object(App\Model\Entity\User)#206 (8) { ["[new]"]=> bool(true) ["[accessible]"]=> array(5) { ["email"]=> bool(true) ["password"]=> bool(true) ["college"]=> bool(true) ["created"]=> bool(true) ["modified"]=> bool(true) } ["[dirty]"]=> array(0) { } ["[original]"]=> array(0) { } ["[virtual]"]=> array(0) { } ["[errors]"]=> array(0) { } ["[invalid]"]=>
array(4) { ["name"]=> string(5) "into" ["email"]=> string(13) "aaa@gmail.com" ["password"]=> string(4) "0000" ["college"]=> string(7) "college" }
\$dataの方を見ると、入力データにはきちんとnameが存在している。
$newの方を見ると、
email, password, college, created, modifiedのキーはあるのに、nameのキーがない。
どうやら、newEntity()に原因があるようだ。公式サイトを調べてみると、
src/Model/Entityの下にある、対象のテーブル名ファイルの$_accessible プロパティーに、追加したカラムを自分で列挙する必要があるとのこと。
自分の場合はUserテーブルのカラムを追加したので、src/Model/Entity/User.phpに以下のコードを追加。
...
protected $_accessible = [
'name' => true, //これを追加
'email' => true,
'password' => true,
'college' => true,
'created' => true,
'modified' => true
];
...
これで再び動作確認をすると、nameがちゃんと保存されました!