Saving Data Changed in a Behavior

I’ve written a behavior to soft-delete records from anywhere in my project. Code follows:

class DeleteBehavior extends Behavior
{
    public function softDelete(EntityInterface $entity, $user)
    { 
        /*  
        *   Set deleted/undeleted condition for entity
        */
        // Undelete the record
        if ($entity->deleted_record == 1) {
            $entity->set('deleted_record', 0);
            $entity->set('deleted_user_id', 0);
            $entity->set('deleted', NULL);
        } else {
            // Delete the record
            $entity->set('deleted_record', 1);
            $entity->set('deleted_user_id', $user->id);
            $entity->set('deleted', date('Y-m-d HH:i:s'));
        }
    }
    public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)
    {  
        $this->softDelete($entity);
    }
}

The behavior is loaded in my ProjectsTable and is called in my ProjectsController:

public function delete($id = null)
{
    $this->request->allowMethod(['post']);
    $project = $this->Projects->get($id);
    $user = $this->request->getAttribute('identity');

    //Delete or undelete based on the current value of deleted_record
    $this->Projects->softDelete($project, $user);
    if ($project->deleted_record == 1) {
        $this->Flash->success(__('The project has been undeleted.'));
    } else {
        $this->Flash->success(__('The project has been deleted.'));
    }
    $this->redirect(['action' => 'index']);
}

Debugging in the behavior shows that the $entity->set values are correct, but I’m unsure how to save them. $entity-save() throws Call to undefined method App\Model\Entity\Project::save(), and patchEntity() throws Call to undefined method App\Model\Behavior\DeleteBehavior::patchEntity(). Here are my use statements:

use ArrayObject;
use Cake\Datasource\EntityInterface;
use Cake\Event\EventInterface;
use Cake\ORM\Behavior;
use Cake\ORM\Entity;
use Cake\ORM\Query;
use Cake\ORM\Table;
use Cake\Validation\Validator;

What should I do to save these $entity->set values once they’re set by my behavior?

Both the save() and patchEntity() methods are on the Table object not the Entity object. I believe that the Table object will be available at getTable() in your behavior so the call would be:

//in DeleteBehavior
$this->getTable()->patchEntity($entity, ['key' => 'value']);
//and
$this->getTable()->save($entity);
1 Like

Thank you! That was the missing piece. Working great now.