Friday, February 4, 2022

[FIXED] CakePHP Behaviors call to behavior method returns error

Issue

I've been working with cakephp for personal use. Now I understood that I want to create some functions that will be repeated in many models of my project, so I found out by Cakephp docs that the best way to do it is using Behaviors.

Objective: Each time a new entity of my project models are created, I want to notice some users(coworkers) by email. Like a new project added, new task added, etc...

What achieved until now I created a behavior with an afeterSave event listener; I attached it in one of my models. When I create I add a new task it runs the behaviors methods and send a simple email.

Problem The problem is to find out witch model has called the event I read the cake2.x docs and the afterSave event used to receive the event and the model in witch you could call alias to know the model name:

public function afterSave(Model $model,...){
     $model_name = $model->alias;
     if ($model_name == 'some_model'){
      //code for specific model
      } else (...)
 }

However in cakephp 3.9 we receive Event and EntityInterface:

public function afterSave(Event $event, EntityInterface $model)
   {
    
    # I tried $mail_HTMLmessage= $model->_registryAlias;
    # I tried $mail_HTMLmessage= $model->_className;
    # I tried $mail_HTMLmessage= $model->get('className');
    $this->sendMail($mail_HTMLmessage);// this is another method that i defined in my behavior that sends an email to me with the string mail_HTMLmessage as the mail message.

     return true;
   }

I've tested mail_HTMLmessage=$event->getName() and in my email I received event.afterSave as expected. However everything I tried to get model/class name it returned an empty string.

Is it possible to get the model name? and what is the best way to do it?

Thanks in advance


Solution

I believe what you're looking for is not in the event at all, but the entity. getSource(), to be specific.



Answered By - Greg Schmidt

No comments:

Post a Comment

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