yBrodsky
yBrodsky

Reputation: 5041

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);
} 

Upvotes: 4

Views: 5750

Answers (4)

Navguls
Navguls

Reputation: 11

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.

Upvotes: 1

eM.
eM.

Reputation: 165

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
    }
}

Upvotes: 14

Avtar Singh
Avtar Singh

Reputation: 21

Another way to write the same code:

public function beforeSave(\Cake\Event\Event $event, \Cake\ORM\Entity $entity, \ArrayObject $options){

    if($entity->isNew()) {
        // on create
    } else {
        // on update
    } 
}

Upvotes: 0

fitorec
fitorec

Reputation: 4765

Yes, your need use Event and Entity object:

check this example:

// src/Model/Table/ArticlesTable.php

use Cake\Event\Event;
use Cake\ORM\Entity;

public function beforeSave(Event $event, Entity $entity) {
    if ($entity->isNew()) {
        return true;
    }
    // edit code
}

Upvotes: 0

Related Questions