在应用程序登录中,我有以下代码,在记录错误时抛出 ...HttpException
:
// common/models/LoginForm.php which is called from the backend SiteController actionLogin method as $model = new LoginForm();
public function loginAdmin()
{
//die($this->getUser()->getRoleValue()."hhh");
if ($this->getUser()->getRoleValue() >= ValueHelpers::getRoleValue('Admin') && $this->getUser()->getStatusValue() == ValueHelpers::getStatusValue('Active')){
if ($this->validate()){
return \Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30:0);
}
else{
throw new \yii\web\NotFoundHttpException('Incorrect Password or Username.');
}
}
else{
throw new \yii\web\ForbiddenHttpException('Insufficient privileges to access this area.');
}
}
它工作正常,但我想自定义使用 NotFoundHttpException
和 ForbiddenHttpException
呈现的页面。我试图搜索 Yii2 api查找任何可能在对象构造中定义 View 的参数,但我找不到。那么,有没有办法自定义异常的 View 呢?
最佳答案
来自Mihai P. (谢谢)回答,我已经得到这个答案了。我打开错误类的文件 vendor\yiisoft\yii2\web\ErrorAction.php
我发现它有一个用于查看的公共(public)属性,因此,我决定使用它,因此我在 actions
方法的 error
数组中定义了它,如下所示:
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
'view' => '@common/views/error.php',
],
];
}
最后,在 common
文件夹中,我必须创建一个名为 views
的新文件夹,并用名为 error.php
的 View 文件填充它简单代码如下
<?php
$this->title = $name;
echo $name;
echo "<br>";
echo $message;
echo "<br>";
echo $exception;
View 中的三个变量$name、$message和$exception
由ErrorAction对象提供,它们可以在last lines of that file中找到。
...
else {
return $this->controller->render($this->view ?: $this->id, [
'name' => $name,
'message' => $message,
'exception' => $exception,
]);
}
...
关于php - Yii2 自定义 http 异常 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28332327/