PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, December 31, 2021

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

 December 31, 2021     cakephp, cakephp-3.0     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing