我正在尝试使用下面的代码在控制器中保存我的表单数据,但是需要它以失败的方式显示并创建和更新错误消息。下面是我的代码,我还在UserTable Model类中添加了行为。我不知道这里错过了什么,请帮助。
用于保存用户数据的控制器代码
public function signup()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->getData());
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
}
debug($user->errors());
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
$this->set(compact('user'));
$this->set('_serialize',['user']);
}
在user.php中,我的访问权限低于$ _accessible
protected $_accessible = [
'display_name' => true,
'email' => true,
'mobile' => true,
'password' => true,
'created_at' => true,
'updated_at' => true
];
并且在UserTable中我也添加了行为
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('users');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
}
保存数据时出现以下错误。
[
'created_at' => [
'_required' => 'This field is required'
],
'updated_at' => [
'_required' => 'This field is required'
]
**In UserTable you can try behavior like this:**
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('users');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp', [
'User' => [
'Model.beforeSave' => [
'created_at' => 'new',
'updated_at' => 'always',
]
]
]);
}