【问题标题】:Debugging save() returning false CakePHP 3.0调试 save() 返回 false CakePHP 3.0
【发布时间】:2015-04-22 05:51:36
【问题描述】:

我有一些代码在某个地方出现了问题,我在调试它时遇到了麻烦。

这是它的简化版本。

$data = $this->request->data;

$form = $this->Forms->get($data['id'], [
    'contain' => ['FieldsForms' => ['data']
    ]
]);

$form = $this->Forms->patchEntity($form, $data,
    ['associated' => [
        'FieldsForms.Data',

    ]
]);

if ($this->Forms->save($form)) {
    // sunshine and rainbows
} else {
    // wailing and gnashing of teeth
}

我一直在哭泣和咬牙切齿,没有任何错误,据我所知,如果我调试 $data,它看起来还可以(尽管它相当长并且包含一堆 UUID,所以我可能会丢失东西)。

验证错误为空。

保存返回错误 - 关于如何调试它的任何建议都可能保存我剩下的理智。

谢谢!

【问题讨论】:

  • 当您说“验证错误为空”时,您如何检查? 之后保存以便包括可能的表规则错误?
  • 视图被渲染并使用调试工具包显示“表单”的验证为空
  • 那么我建议挖掘 CakePHP 核心源代码来调试源自 Table::save() 调用的控制流。

标签: debugging cakephp save cakephp-3.0


【解决方案1】:

问题出在数据上,不出所料,但无法立即看到,因为保存返回 false 并且数据很大。

我首先制作了显示相同行为的问题数据子集,然后按照 ndm 的建议,更改了保存功能的 ORM/Table.php 代码,如下所示,以便能够查看问题所在:

// $entity->errors() is deprecated as of CakePHP 3.7
// $entity->getErrors() should be used in later versions
$x = $entity->errors();
if ($x) {
    debug($entity);
    debug($x);
    return false;
}

这样我就可以看到发生了什么并继续修复数据。

【讨论】:

  • 丰富 - 这太棒了。奇迹般有效。有没有办法通过覆盖应用程序代码中的 Table 类来实现这一点,而不是修改核心?谢谢。
  • $entity->getErrors() 应该在 CakePHP 3.7 及更高版本中使用而不是 $entity->errors()。
【解决方案2】:

对于 CakePHP 3.4.*

试试这个代码:

if (!$this->Forms->save($form)) {
    $this->log($form->getErrors(),'error');
}

在此处阅读有关日志的更多信息:https://book.cakephp.org/3.0/en/core-libraries/logging.html#using-the-filelog-adapter

【讨论】:

    【解决方案3】:

    不确定较早的答案是否基于旧版本,但在最新的 cakephp 版本(3.4)中,您可以直接从控制器中的 $entity 检索错误。 errors 数组包含每个失败的实体字段,以及失败验证的子数组。

    <?php
    // In Articles Controller
    ...
    
    public function add(){
    ...
      if ($this->Articles->save($article)) {
        $this->Flash->success(__('The Article has been saved.'));
        return $this->redirect(['action' => 'index']);
      } else {
        Log::Debug($article->errors());
      }
    

    【讨论】:

    • 使用 cakephp 3.3.* 非常感谢我的一个向上箭头!
    • 对我来说,以下方法效果很好:}else{debug($item->errors());} 虽然我想知道为什么调试 $item 值不默认显示 $item 对象的错误部分。如果通过简单地“(简单地调试被操纵的值(在我的例子中是 $item,或者这里的 $article)可以直接看到这些最终错误)会更容易。
    【解决方案4】:

    改为修改核心 Cake 代码,您可以这样做:

    if ($this->Forms->save($form)) {
        // sunshine and rainbows
    } else {
        //you know now what fail
        $andTheErrorsAre = $entity->getErrors();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-09
      相关资源
      最近更新 更多