Friday, December 31, 2021

[FIXED] how to implement beforeDelete() event in cakephp 3 for all models

Issue

In cakephp 3 we can define beforDelete event listener in any Model. But how to use this event for all models. I want to detect all cascade records conditions before delete one record in all exists models.

namespace App\Model\Table;

use Cake\ORM\Table;

class ArticlesTable extends Table{

    public function initialize(array $config)
     {
        $this->primaryKey('my_id');
     }

    public function beforeDelete(Event $event, EntityInterface $entity,ArrayObject $options)
    {
       return false;
    }
}

how to use this code for all models. should be this code in appcontroller?


Solution

I usually create behavior class and add the functionality there which will be shared by most of the Table objects. I don't know it's better approach or not but here are the steps i follow.

First create behavior class with bake command bin/cake bake behavior , this will create properly namespaced class , and add beforeDelete method there. Include use ArrayObject; use Cake\Event\Event; use Cake\ORM\Entity;at the top if bake command hasn't added already.

public function beforeDelete(Event $event, Entity $entity, ArrayObject $options){
    //your code goes here
   // $this->_table is Table object instance behavior is attached to
}

Now attach behaviour to your Table classes

class ArticlesTable extends Table{
    public function initialize(array $config)
    {
       $this->addBehavior('YourBehaviorNeme');
    }
}

For more info see http://book.cakephp.org/3.0/en/orm/behaviors.html



Answered By - N Nem

No comments:

Post a Comment

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