How to use beforeSave in CakePHP 3? $event, $entity and $options must be always filled?

I Wanna Know picture I Wanna Know · May 8, 2015 · Viewed 15.6k times · Source

I'm inside "PostsTable.php" I'm trying to get form data to treat image files.

In CakePHP 2, I used to do:

public function beforeSave($options = array())
{
if(!empty($this->data['Post']['picture']['name'])...

Someone could explain this in Cake 3:

beforeSave
Cake\ORM\Table::beforeSave(Event $event, Entity $entity, ArrayObject $options)

?

ADDED

I try this snippet of code to see if I'm able to save this field on database just as a test but it seems beforeSave is being ignored:

public function beforeSave($options)
{ 
if(!empty($entity->pic1['name'])) 
{ 
$entity->pic1 = 'jus a test';
}

Thanks

Answer

Naidim picture Naidim · Aug 1, 2016

Start with the function definition.

Cake\ORM\Table::beforeSave(Event $event, EntityInterface $entity, ArrayObject $options)

Since CakePHP is calling the function automatically, this is how it is being called, so build your function identically to the function definition:

// In PostsTable.php
public function beforeSave($event, $entity, $options) {

}

If you aren't sure what data is being sent, use CakePHP's debug() function:

    debug($event); debug($entity); debug($options);

Once you find your data in $entity use it to do what you want to do to your data:

    if (!empty($entity->picture['name'])) { ...