Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 754
I Wanna Know Avatar asked May 08 '15 12:05

I Wanna Know


1 Answers

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'])) { ...
like image 186
Naidim Avatar answered Nov 16 '22 03:11

Naidim