Yii2:不是特定于属性的验证错误 [英] Yii2: validation errors that are not attribute specific

查看:76
本文介绍了Yii2:不是特定于属性的验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何处理与特定属性无关的Yii2 ActiveRecord模型中的通用验证错误?例如,当相关记录/模式设置为非活动状态时,我需要完全禁止保存模型.

How do I handle generic validation errors in a Yii2 ActiveRecord model that do not relate to a specific attribute? For example I need to completely prohibit saving a model when a related record/modal has been set to inactive.

我当然可以选择一个或多或少的随机属性,然后将错误消息分配给它,但是如果前端表单不具有该属性,因此不显示错误怎么办?甚至更糟的是,如果以后某个场景禁用了对该属性的验证(通过不将其包括在活动属性列表中)?

I can of course just pick a more or less random attribute and assign the error message to it, but what if the front end form doesn't have that attribute and therefore doesn't show the error? Or even worse, if a scenario later disables validation of that attribute (by not including it in the list of active attributes)?

我当然可以在beforeSave()beforeValidate()中返回false,但是然后我没有选择向用户指定一条消息,说明为什么无法保存模型,所以我真的不喜欢这个想法.

I can of course return false in beforeSave() or beforeValidate() but then I have no option to specify a message to the user about why the model couldn't be saved, so I really don't like that idea.

此外,我也不想抛出异常,它应该只是向用户显示的软错误消息.

Also, I don't want to throw Exceptions, it should just be a soft error message shown to the user.

处理此问题的最佳意图/方法是什么?

What is the intended/best approach to handle this?

推荐答案

您是否研究过

have you looked into flash data they can be used for this purpose to show messages like success, errors and warnings which are or are not specific to your model attributes. It's up to you where you want o use them.

我主要是在 块,当我保存多个模型时,我使用try catch块获取发生的任何模型的错误,并使用会话闪存以及

I mostly insert data or save models within transaction block and there when I am saving multiple models I use try catch block to get the errors for any models that occur and use session flash along with ArrayHelper to add errors in the flash message.

您可以按照以下方式使用它.

For your purpose you can use it the following way.

使用

Yii::$app->session->setFlash('error','you are not allowed to perform this message');

,您可以在视图中使用以下内容获取它

and you can get it using the following inside your view

if(Yii::$app->session->hasFlash('error')){

echo Yii::$app->session->gettFlash('error');

}

对此更复杂的方法是 \kartik\widgets\AlertBlock

a more sophisticated approach towards this is \kartik\widgets\AlertBlock

使用作曲家安装

php composer.phar require kartik-v/yii2-widget-alert "*"

然后使用以下代码在layouts文件夹中创建一个名为alerts.php的文件

Then create a file called alerts.php in layouts folder with the following code

use kartik\widgets\AlertBlock;

AlertBlock::widget (
        [
            'useSessionFlash' => false ,
            'type' => AlertBlock::TYPE_GROWL ,
            'alertSettings' => [
                'settings' => [
                    'type' => kartik\widgets\Growl::TYPE_SUCCESS ,
                    'icon' => 'glyphicon glyphicon-ok-sign' ,
                    'title' => 'Note' ,
                    'showSeparator' => true ,
                    'body' => Yii::$app->session->getFlash ( 'success' )
                ] ,
            ]
] );

AlertBlock::widget (
        [
            'useSessionFlash' => false ,
            'type' => AlertBlock::TYPE_GROWL ,
            'alertSettings' => [
                'settings' => [
                    'type' => kartik\widgets\Growl::TYPE_INFO ,
                    'icon' => 'glyphicon glyphicon-ok-sign' ,
                    'title' => 'Note' ,
                    'showSeparator' => true ,
                    'body' => Yii::$app->session->getFlash ( 'info' )
                ] ,
            ]
] );


AlertBlock::widget (
        [
            'useSessionFlash' => false ,
            'type' => AlertBlock::TYPE_GROWL ,
            'alertSettings' => [
                'settings' => [
                    'type' => kartik\widgets\Growl::TYPE_DANGER ,
                    'icon' => 'glyphicon glyphicon-ok-sign' ,
                    'title' => 'Note' ,
                    'showSeparator' => true ,
                    'body' => Yii::$app->session->getFlash ( 'error' )
                ] ,
            ]
] );


AlertBlock::widget (
        [
            'useSessionFlash' => false ,
            'type' => AlertBlock::TYPE_GROWL ,
            'alertSettings' => [
                'settings' => [
                    'type' => kartik\widgets\Growl::TYPE_DANGER ,
                    'icon' => 'glyphicon glyphicon-ok-sign' ,
                    'title' => 'Note' ,
                    'showSeparator' => true ,
                    'body' => Yii::$app->session->getFlash ( 'danger' )
                ] ,
            ]
] );


AlertBlock::widget (
        [
            'useSessionFlash' => false ,
            'type' => AlertBlock::TYPE_GROWL ,
            'alertSettings' => [
                'settings' => [
                    'type' => kartik\widgets\Growl::TYPE_WARNING ,
                    'icon' => 'glyphicon glyphicon-ok-sign' ,
                    'title' => 'Note' ,
                    'showSeparator' => true ,
                    'body' => Yii::$app->session->getFlash ( 'warning' )
                ] ,
            ]
] );

,然后在如下所示的$this->beginBody()调用之后将其包含在布局文件中

and then include it in your layout file after $this->beginBody() call like below

<?= Yii::$app->view->renderFile ( '@frontend/views/layouts/alerts.php' ); ?>

那么您只需要设置即显消息,就是说您甚至不必调用getFlash(),如果您拥有以下可用变量,扩展程序就会自动显示该消息

then you just have to set the flash message and that is it you won't even have to call getFlash(), the extension will display it automatically you have the following variables available

  • 成功
  • 信息
  • 危险
  • 警告
  • 错误

使用Yii::$app->session->setFlash('danger','You cannot do this');

注意:每次在设置Flash消息后进行重定向时,请记住将returnredirect()一起使用,否则您可能会遇到消息未显示的问题.

Note: Whenever you are redirecting after setting the flash message remember to use return along with redirect() otherwise you may face the problem that the messages are not showing up.

return $this->redirect(['index']);

您正在尝试为与当前正在保存的模型相关的任何特定模型添加错误消息,并且您需要一些灵魂技巧,以允许您引发异常并在格式正确的错误消息中显示异常,因此您遇到了问题所面临的是设置错误消息,如果我愿意的话,我将使用以下方法.可以说我有一个actionTest(),如下所示,它保存了提交时的表单.

you are trying to add an error message for any particular model that is related to the model currently being saved and you want some soultion that would allow you to throw exceptions and show them in a nicely formatted error message, so the problem you are facing is setting the error message, if i would do it i would use the following approach. Lets say i have a actionTest() like below which is saving the form on submission.

public function actionTest() {

    $model = new Campaign();

    if ($model->load(Yii::$app->request->post())) {

        //start transaction block
        $transaction = Yii::$app->db->beginTransaction();

        try {
            if (!$model->save()) {
                //throw an exception if any errors
                throw new \Exception(implode("<br />",\yii\helpers\ArrayHelper::getColumn($model->errors, 0,false)));
            }
            //commit the transaction if there arent any erorrs to save the record
            $transaction->commit();

        } catch (\Exception $ex) {

            //roll back the transaction if any exception
            $transaction->rollBack();

            //catch the error and display with session flash
            Yii::$app->session->setFlash('danger',$ex->getMessage());
        }
    }
    $this->render('test');
}

这篇关于Yii2:不是特定于属性的验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆