Sunday, February 13, 2022

[FIXED] cakephp use record values in afterDelete

Issue

I am using the soft delete plugin for my EmployeesTable.php in CakePHP 3.0.

When I soft delete an employee I wish to update their associated user table with $user->set('active', false); within the afterDelete()

My problem is getting the user_id used in the employees table into the afterDelete()

I have even tried to just the id of the employee deleted and do a find on that but the examples I have seen using the $this->id return and error Table "App\Model\Table\EmployeesTable" is not associated with "id" from the beforeDelete.

EmployeesTable.php

public function afterDelete( ) {
    $user = $this->Users->get($this->user_id);
    $user->set('active', false);
    $this->Users->save($user);
}

I have also tried catching $this->id in beforeDelete() and passing it to the afterDelete() but again get the error Table "App\Model\Table\EmployeesTable" is not associated with "id"


Solution

private $deletedUserId;

public function beforeDelete($event, $entity, $options) {
    $this->deletedUserId = $entity->user_id;
}

public function afterDelete( ) {
    $user = $this->Users->get($this->deletedUserId);
    $user->set('active', false);
    $this->Users->save($user);
}


Answered By - Keith Power

No comments:

Post a Comment

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