10-13-7
10-13-7

Reputation: 1

Check if data exist before saving in cakephp

I am quite new to cake3 I don't know if how can manage to do this I have two

table users and accounts

users contain

Id,EmployeeId,Password,Logs 

accounts contain

Id,EmployeeId,Password,Fname,Lname,Role 

What I want to happen is before the data is save in users table it will check first if the Employee Id and Password is present in the accounts table how do I do this in cakephp 3?

I have this in one of my controllers

$user = $this->Users->newEntity();
        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->data);
            if ($this->Users->save($user)) {
                $this->Flash->success(__('Log Time Saved!.'));
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The user could not be saved. Please, try again.'));
            }
        }
        $this->set(compact('user'));
        $this->set('_serialize', ['user']);

Upvotes: 0

Views: 1218

Answers (1)

flangofas
flangofas

Reputation: 332

In CakePHP 3:

You should use BeforeSave callback where the Entity object is passed as a parameter and you can use it to check if the same record exists and avoid from storing it again.

From the documentation:

The Model.beforeSave event is fired before each entity is saved. Stopping this event will abort the save operation. When the event is stopped the result of the event will be returned.

Upvotes: 1

Related Questions