PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 1, 2022

[FIXED] Cakephp Saving User Data is failing with timestamp error

 January 01, 2022     cakephp, cakephp-3.0, cakephp-model     No comments   

Issue

I am trying to save my form data with below code in controller but its failing with error message stating created and updated is required. Below is my code, I have also added the behaviour in the UserTable Model class. I do not know what is missed here, please help.

controller code to save user data

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']);
}

in user.php i have below $_accessible

protected $_accessible = [
    'display_name' => true,
    'email' => true,
    'mobile' => true,
    'password' => true,
    'created_at' => true,
    'updated_at' => true
];

and in UserTable i have added the behaviour too

public function initialize(array $config)
{
    parent::initialize($config);

    $this->setTable('users');
    $this->setDisplayField('id');
    $this->setPrimaryKey('id');
    $this->addBehavior('Timestamp');
}

I get the below error on saving the data.

[
'created_at' => [
    '_required' => 'This field is required'
],
'updated_at' => [
    '_required' => 'This field is required'
]

Solution

**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',
            ]
        ]
    ]);
}


Answered By - Dev Rupinder
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing