Cakephp保存用户数据失败,出现时间戳错误

问题描述 投票:0回答:1

我正在尝试使用下面的代码在控制器中保存我的表单数据,但是需要它以失败的方式显示并创建和更新错误消息。下面是我的代码,我还在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'
]
cakephp cakephp-3.0 cakephp-model
1个回答
0
投票
**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',
            ]
        ]
    ]);
}
© www.soinside.com 2019 - 2024. All rights reserved.