CakePHP 3 - beforeSave回调无法编辑

问题描述 投票:3回答:3

我有一个beforeSave-callback,每当我创建一个新实体时都会调用它。但是当我编辑时,它根本就没有被调用。在文档中找不到任何可能有用的内容。

这是我的编辑功能:

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);
} 
cakephp callback edit cakephp-3.0
3个回答
14
投票

仅当您发布/编辑的数据被修改时,才会触发beforeSave函数。

//triggers only if an entity has been modified
public function beforeSave(Event $event, Entity $entity)
{
    if($entity->isNew()) {       
        //on create
    } else {
        //on update
    }
}

0
投票

是的,你需要使用EventEntity对象:

检查这个例子:

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

0
投票

编写相同代码的另一种方法:

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

    if($entity->isNew()) {
        // on create
    } else {
        // on update
    } 
}
© www.soinside.com 2019 - 2024. All rights reserved.