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);
} 
                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
    }
}
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With