beforeSave within behavior not called using CRUD (friendsOfCake)

behavior
#1

Hello there!

I got a strange problem. I created a behavior what adds a default timezone-string (iana-code) to a entity-/db-field. Therefore, I added a “beforeSave()” method to the class and it works as expected through the application.

But when request came through the rest api (rest including friendsofcake/crud), the entity will tried to be saved, the behavior is called (initialize()-method of the behavior), but not the part with the logic (beforeSave), so the entity won’t have the timezone-string and thus, saving fails with a mysql-exception. No matter, what signature “beforeSave” is of, the method is never executed. The api-controller is empty as crud handles all logic.

Can sb. help me out? Thanks in advance.

class TagsController extends AppController
{
}

class TimezoneBehavior extends Behavior
{
    public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $object) {
        die("I WON'T BE EXECUTED VIA REST API REQUEST");
        foreach($this->_defaultConfig['fields'] as $field) {
            $entity->set($field, $this->getTimezone());
        }
    }
}
0 Likes

#2

Yesterday, I tried to find a solution for at least two hours. After posting this, I wanted to check other things in AppController (api) and found this piece of code:

    //globally remove Timezone-Behavior from Model, we expect it to be sent via api.
    $model = $this->getTableLocator()->get($this->modelClass);
    if($model->hasBehavior("Timezone")) {
        $model->removeBehavior("Timezone");
    }

The comment and code speaks for itself. I just forgot about this implementation.

So please delete this topic, as there is actually no error.

Positive side-effect: Now using cake 3.7 and all packages are up to date… :wink:

0 Likes