我有一个带有电子邮件和密码的用户模型。我将字段first_name和last_name添加到我的数据库,添加视图的表单如下:
9 <div class="users form large-12 medium-9 columns">
10 <?= $this->Form->create($user) ?>
11 <fieldset>
12 <legend><?= __('New Account') ?></legend>
13 <?php
14 echo $this->Form->input('email');
15 echo $this->Form->input('first_name');
16 echo $this->Form->input('last_name');
17 echo $this->Form->input('password');
18
19 ?>
20 </fieldset>
21 <?= $this->Form->button(__('Submit')) ?>
22 <?= $this->Form->end() ?>
23 </div>
电子邮件和密码保存没有问题,但first_name和last_name永远不会。这是控制器功能。添加注释行会导致first_name字段保存,但很明显我不应该这样做。
46 public function add()
47 {
48 $user = $this->Users->newEntity();
49 if ($this->request->is('post')) {
50 $user = $this->Users->patchEntity($user, $this->request->data);
51 //$user->first_name = $this->request->data['first_name'];
52 if ($this->Users->save($user)) {
53 $this->Flash->success(__('The user has been saved.'));
54 return $this->redirect(['action' => 'index']);
55 } else {
56 $this->Flash->error(__('The user could not be saved. Please, try again.'));
57 }
58 }
59 $books = $this->Users->Books->find('list', ['limit' => 200]);
60 $this->set(compact('user', 'books'));
61 $this->set('_serialize', ['user']);
62 }
有谁知道为什么会这样?我尝试清除模型缓存但没有任何改变。
谢谢!
答案 0 :(得分:0)
使用
批量分配新属性$this->Model->patchEntity($entity, $this->request->data);
你必须将它们列入白名单。在这种情况下,在/src/Model/Entity/User.php文件中:
1 protected $_accessible = [
2 'email' => true,
3 'password' => true,
4 'first_name' => true, //add this
5 'last_name' => true, //add this
6 ];
另一方面,总是可以直接分配属性(如$user->first_name = $this->request->data['first_name'];
中所示)。
更多信息:http://book.cakephp.org/3.0/en/orm/entities.html#mass-assignment
答案 1 :(得分:0)
另一种方法是在创建实体时设置可通信字段。
$user = $this->Users->newEntity($this->request->data, [
'accessibleFields' => [
'email' => true,
'password' => true,
'first_name' => true,
'last_name' => true, //or you could just use '*' => true
]
]);
也没有必要使用数据调用newEntity然后调用patchEntity,你可以在我的示例中首先将数据提供给newEntity