Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP 3 - beforeSave callback not working on edit

I have a beforeSave-callback which is called just fine whenever I create a new entity. However when I am editing, it's not called at all. Could not find anything in the documentation that could be helpful.

Here's my edit function:

public function edit($id = null) {
    if (!$id) {
        throw new NotFoundException(__('Invalid article'));
    }

    $article = $this->Articles->get($id);
    if ($this->request->is(['post', 'put'])) {
        $this->Articles->patchEntity($article, $this->request->data);
        if ($this->Articles->save($article)) {
            $this->Flash->success(__('Your article has been updated.'));
            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('Unable to update your article.'));
    }

    $this->set('article', $article);
} 
like image 359
yBrodsky Avatar asked Dec 06 '22 22:12

yBrodsky


2 Answers

The beforeSave function will be triggered only if the data you post/edit is modified.

//triggers only if an entity has been modified
public function beforeSave(Event $event, Entity $entity)
{
    if($entity->isNew()) {       
        //on create
    } else {
        //on update
    }
}
like image 195
eM. Avatar answered Dec 25 '22 17:12

eM.


I also had the problem that the tutorial got stuck on this point, but I used the bin/cake bake command to autogenerate the ArticlesTable code and it added this validator:

$validator
        ->scalar('slug')
        ->maxLength('slug', 191)
        /*->requirePresence('slug', 'create')*/
        ->notEmptyString('slug')
        ->add('slug', 'unique', ['rule' => 'validateUnique', 'provider' => 'table']);

When I commented the requirePresence() it solved this issue for me. If you have requirePresence('fieldName', 'create') for validation, you will get an error if you don't have that field on a post when creating the new Article entity.

like image 29
Navguls Avatar answered Dec 25 '22 18:12

Navguls