phpcakephpcakephp-3.0before-saveafter-save

CakePHP 3 - Use saved data inside afterSave()


I have submitted a form in my view which will be processed in the controller. What normally happens is that the controller saves the edits by doing this:

if ($this->Requests->save($request)) {
    // the request have been saved.
}

Now I created another insert query to follow the activity of the editor with the afterSave() statement like so:

public function afterSave()
{
    // here I need the data submitted from $this->request->save($request));
    // how can I do this to use the data in the query?

    // insert query here.
}

I want to use the afterSave() because I want to use it for all changes made to the requests, but I can't seem to find a way to access the posted data.

The documentation says that the afterSave() contains the following parameters:

afterSave(Event $event, EntityInterface $entity, ArrayObject $options)

Do I need these to accomplish what I want? If so, how do I use those properly? because I can't seem to get any debug information to see what it contains of the save action.

The question is as follows:

How can I access the data saved with $this->Requests->save($request) in a beforeSave() or afterSave() statement to use the data in another query?


Solution

  • How can I access the data saved with $this->Requests->save($request) in a beforeSave() or afterSave() statement to use the data in another query?

    The 2nd arg of both callbacks is the entity data. Unless you need the whole request you can get all the data that was converted by the marshaller into an entity from the 2nd arg $entity. Check the documentation on the methods:

    I don't know what your problem is but doing debug($entity); there will show the entity data. If not something else is wrong in your code.

    Just use the entity for doing whatever you want there.