php - Yii2删除ActiveRecord错误消息有时是数组,有时不是吗?

标签 php activerecord error-handling yii2 delete-row

我在Controller中有这个,它是用巨型生成的(我认为这是正确的):

public function actionDelete($id) {
    try {
        $this->findModel($id)->delete();
    } catch (\Exception $e) {
        $msg = (isset($e->errorInfo[2])) ? $e->errorInfo[2] : $e->getMessage();
        \Yii::$app->getSession()->addFlash('deleteError', $msg);
        return $this->redirect(Url::previous());
    }

    $isPivot = strstr('$id', ',');
    if ($isPivot == true) {
        return $this->redirect(Url::previous());
    } elseif (isset(\Yii::$app->session['__crudReturnUrl']) && \Yii::$app->session['__crudReturnUrl'] != '/') {
        Url::remember(null);
        $url = \Yii::$app->session['__crudReturnUrl'];
        \Yii::$app->session['__crudReturnUrl'] = null;

        return $this->redirect($url);
    } else {
        return $this->redirect(['index']);
    }
}
现在我的问题是,它有时将$msg作为数组抛出,我不知道为什么。
查看/索引:
if (\Yii::$app->session->getFlash('deleteError') !== null) {
    echo Alert::widget([
        'options' => ['class' => 'alert-danger'],
        'body' => \Yii::$app->session->getFlash('deleteError'),
    ])
;}
错误信息:

PHP Notice – yii\base\ErrorException

Array to string conversion


我不知道为什么有时有时而不是为什么。所有 Controller 都是相同的,但对于某些模型,它起作用,而对于某些模型,它不是。我可以实现一种if is_array then ...[0] otherwise ...的解决方法,但我认为这不是解决问题的正确方法。模型如何更改此错误消息的数据类型?您能指出我正确的方向吗?非常感谢。

最佳答案

首先,您实际上从未在此处使用模型验证,因此它与模型无关。其次,$msg可能还可以,问题是您如何使用 getFlash() 。此方法可能返回数组,这是预期的并已记录在案:

The flash message or an array of messages if addFlash was used.



您应该遍历getFlash()结果通过字符串来获取实际消息,或者使用将处理该问题并从getFlash()结果生成多个警报的小部件。

您也可以使用 setFlash() 代替addFlash()。但是我不建议这样做-很容易覆盖以前的某些闪烁,并且您不应该盲目地认为getFlash()结果将是字符串。

关于php - Yii2删除ActiveRecord错误消息有时是数组,有时不是吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50944953/

相关文章:

mysql - 具有数组条件的 Rails 4 LIKE 查询 - 撇号用双反斜杠转义

ruby-on-rails - 是否有可能知道使用 ruby​​ on rails 中的观察器到底发生了什么变化?

ruby-on-rails-3 - "TypeError: no implicit conversion of nil into String"急切加载结果时

actionscript-3 - AIR-抑制调试应用程序中的错误消息?

asp.net - 如何: Dnn Custom Error Pages

php - session 值不会出现

php - 将表单信息发送到数据库时,它只会发送一堆0

php - 如何调试 MySQL/Doctrine2 查询?

php - hotmail:使用 PHP 进行用户身份验证和联系人检索

matlab - rm ANOVA(Matlab)期间具有随机因子的误差