【问题标题】:CakePHP - CRUD API: Error upon inserting to database CakePHPCakePHP - CRUD API:插入数据库 CakePHP 时出错
【发布时间】:2016-06-09 19:44:19
【问题描述】:

我在尝试 POST 到 API 时收到以下错误。我已经按照本书的this 教程进行操作,所以我不确定为什么插入不起作用。

Message: Call to member function error() on boolean
Trace:   ControllerTrait.php

我的 add 函数是通过 bake 制作的,但尽管如此,在保存实体期间似乎发生了错误。

public function add()
    {
        $author = $this->Authors->newEntity();
        if ($this->request->is('post')) {
            $author = $this->Authors->patchEntity($author, $this->request->data);
            if ($this->Authors->save($author)) {
                $this->Flash->success(__('The author has been saved.'));
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The author could not be saved. Please, try again.'));
            }
        }
        $this->set(compact('author'));
        $this->set('_serialize', ['author']);
    }

【问题讨论】:

  • 错误信息本身只是因为没有加载flash组件。

标签: cakephp crud


【解决方案1】:

您不需要 add 操作,只需将其删除 - 这正是 CRUD 插件为您所做的。

如果你需要自定义一个CRUD动作你需要在最后return $this->Crud->execute(),例如:

public function add()
{
  $this->Crud->on('beforeSave', function (Event $e) {
    // Custom logic before save
  });

  // Make sure CRUD takes care of the rest
  return $this->Crud->execute();
}

但是是的,如果您将 add 方法全部删除,它将起作用。

【讨论】:

  • 非常感谢!我已经为此苦苦挣扎了好几个小时
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-10
  • 2015-08-23
  • 2016-12-09
  • 1970-01-01
  • 2021-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多