Wrong implementation of beforeSave event on my side?

I’m trying to overwrite the beforeSave Method in one of my Tables.
Implemented the event as described in the docs, the function is however never reached/called.
My code looks like this:

What am I missing?
Do I need to tell the table somewhere explicitly to use this event?

    public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)
        /** @var \App\Model\Table\ApartmentsTable $apartmentsTable */
        /**@var \App\Model\Entity\RentalContract $entity */
        $apartmentsTable = TableRegistry::getTableLocator()->get('Apartments');
        $oldApartmentId = $entity->getOriginal('apartment_id');

        if ($entity->apartment_id) {

        if ($oldApartmentId) {


Check the type of the table object you’re using to save the entity, to make sure it’s the class you expect it to be.

It definitely targets the correct Table (RentalContracts)

What does debug(get_class($this->RentalContracts)); tell you?

Any chance that it’s aborting the save before it gets to that event, due to validation errors?

Found the problem. I’m using a Behavior in RentalContracts that I made myself which overrides the beforeMarshal Method. If I comment that out, it reaches the beforeSave method. I still don’t understand why that ignores the beforeSave method from the RentalContracts then. Got any clue what could cause that?

A function in a behavior should not “override” the function in the table. It should be called in addition to that other function. (I don’t recall what order they are called in; I’d guess it’s the table first, then any behaviors.)

You say your beforeSave is not reached. I am assuming that this means the entity is not saved. Is that correct? Like, your ->save(...) call return false? Have you checked whether the entity has validation errors in it at that point (i.e. after the save fails)?

No, the entity is saved. Any modification of data that is done in the form is saved. Returns the correct Flash->success message as well. Override was maybe a bad choice of words. The beforeMarshal is implemented the same way in my behavior as in this example from the docs, just don’t have any defaultConfig properties and no slug function

So, just to confirm, the entity is successfully saved whether or not this behavior is included, but if it is included then the table’s beforeSave function never gets called, and if it isn’t included the table’s beforeSave function does get called?

Correct as you described it

Well that’s just bizarre. I have no idea why that might happen. Looks like it’s a debugging exercise for you.

Try leaving the behavior in place, but remove everything in it? If that fixes it, add bits back until it breaks? Use xdebug to step through the save process and see if you can narrow down the problem?

1 Like