Reputation: 411
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
Reputation: 332
Another solution that will work for all models is to:
class MyTable extends Table
beforeDelete
method in that classMyTable
Upvotes: 0
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
Reputation: 25698
This is pretty easy by using the event system. Read the whole chapter to understand the events first.
Upvotes: 4