CakePHP 3 - beforeSave 回调在编辑时不起作用

标签 cakephp callback edit cakephp-3.0

我有一个 beforeSave 回调,每当我创建新实体时都会调用它。然而,当我编辑时,它根本没有被调用。 在文档中找不到任何有用的内容。

这是我的编辑功能:

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

最佳答案

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

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

关于CakePHP 3 - beforeSave 回调在编辑时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29663990/

相关文章:

javascript - 在显示接收到的数据之前等待 Node 中的函数完成

c++ - 我有一个要使用源代码编辑的 .dll。我需要编辑哪些文件?

javascript - cakephp + extjs = b 为空 || ct 为空

php - 每个 CakePHP 1.3 页面请求的 httpd.exe 使用率很高

c - 为什么返回 float 的函数不适用于 void* 回调?

Android:编辑项目属性 - 更改应用程序名称

ExtJS 4-如何有条件地编辑网格中的单元格?

mysql - CakePHP 3 - 1054 找不到列

cakephp - Coffeescript 和 CakePHP

javascript - 很难理解回调函数