脚本在尝试使用 $model->save() 时死掉

Script dies when trying to use $model->save()

我正在尝试使用 $model->save() .. 但我无法获得文档中的错误消息,而是出现带有跟踪错误的错误消息,然后脚本终止。

例如我正在尝试使用此代码:

$user = new Users();
$user->name = "Name";

if(!$user->save()){
   //do stuff if there is an error
}

问题是我总是收到这样的验证错误并且脚本死掉并且永远不会 returns false 进入 if 条件:

password is required
#0 ..../UsersController.php(106): Phalcon\Mvc\Model->save()
#1 [internal function]: ....\UsersController->createAction()
#2 [internal function]: Phalcon\Dispatcher->callActionMethod(Object(....\UsersController), 'createAction', Array)
#3 [internal function]: Phalcon\Dispatcher->_dispatch()
#4 [internal function]: Phalcon\Dispatcher->dispatch()
#5 ....\public\index.php(41): Phalcon\Mvc\Application->handle()
#6 {main}**

我终于找到了解决方案,我发现在 services.php 此行已启用,导致抛出异常的原因 Phalcon\Mvc\Model::setup(['exceptionOnFailedSave' => true] 将其设置为 false 后,我可以轻松添加条件并使用此代码检查错误消息。

if ($model->save() === false) {
    $messages = $model->getMessages();
    foreach ($messages as $message) {
        echo $message, "\n";
    }
}

您可以使用

发送 flash 错误
$this->flash->error("too bad! the form had errors");
$this->flash->success("yes!, everything went very smoothly");
$this->flash->notice("this a very important information");
$this->flash->warning("best check yo self, you're not looking too good.");

查看文档 https://docs.phalconphp.com/en/latest/reference/flash.html