【问题标题】:CakePHP 3 - beforeSave callback not working on editCakePHP 3 - beforeSave 回调在编辑时不起作用
【发布时间】:2015-04-16 01:48:27
【问题描述】:

我有一个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);
} 

【问题讨论】:

  • 您确定您的保存操作一开始就做到了那么远吗?即,它成功了吗?因为如果是这样,那么我会有点怀疑事件没有被分派,因为这发生在插入和更新的同一方法中。
  • 请把beforeSave-callback的代码也贴出来。
  • 我确定是因为记录被修改了。在我的 beforeSave 中,我只是调用了一个 die(),所以它不会在我不注意的情况下调用它。
  • 好吧,如果记录正在被保存,那么事件正在被调度,除非调度器被破坏。检查$this->Articles 实例是否真的是实现了回调方法的实际表类(debug(get_class($this->Articles)))的实例,而不是“自动表”(Cake\ORM\Table 的实例),还要确保您不要惹Table::implementedEvents()
  • 今晚晚些时候会检查并回复您。感谢您的帮助。

标签: cakephp callback edit cakephp-3.0


【解决方案1】:

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

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

【讨论】:

  • 我不确定谁否决了这个答案,因为它基本上是正确的。
【解决方案2】:

我也遇到了教程卡在这一点上的问题,但我使用 bin/cake bake 命令自动生成 ArticlesTable 代码并添加了这个验证器:

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

当我评论 requirePresence() 时,它为我解决了这个问题。如果您有 requirePresence('fieldName', 'create') 进行验证,如果您在创建新的 Article 实体时在帖子中没有该字段,则会收到错误消息。

【讨论】:

    【解决方案3】:

    是的,您需要使用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
    }
    

    【讨论】:

      【解决方案4】:

      同样代码的另一种写法:

      public function beforeSave(\Cake\Event\Event $event, \Cake\ORM\Entity $entity, \ArrayObject $options){
      
          if($entity->isNew()) {
              // on create
          } else {
              // on update
          } 
      }
      

      【讨论】:

        猜你喜欢
        • 2012-04-26
        • 1970-01-01
        • 1970-01-01
        • 2012-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多