Saeid Dadkhah
Saeid Dadkhah

Reputation: 411

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

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?

Upvotes: 2

Views: 2257

Answers (3)

r34
r34

Reputation: 332

Another solution that will work for all models is to:

  1. Create class MyTable extends Table
  2. Define beforeDelete method in that class
  3. Make all other table classes extend MyTable

Upvotes: 0

Nabin  Nembang
Nabin Nembang

Reputation: 753

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

Upvotes: 2

floriank
floriank

Reputation: 25698

This is pretty easy by using the event system. Read the whole chapter to understand the events first.

  1. Create an event listener that listens to this event
  2. Do whatever you want in the listeners callback method, add your logic there
  3. Attach the listener to the global event manager in your bootstrap.php

Upvotes: 4

Related Questions