Yii2 自定义客户端验证,在模态中使用 ajax 渲染 [英] Yii2 custom client validation with ajax rendering in modal

查看:11
本文介绍了Yii2 自定义客户端验证,在模态中使用 ajax 渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有自定义验证方法的模型.为了测试,它总是返回一条错误消息.

公共函数规则(){返回 [...['staff_ids', 'each', 'rule' =>['细绳']],[['staff_ids'], 'validateStaffIds'],...];}公共函数 validateStaffIds($attribute, $params, $validator) {$this->addError($attribute, '员工 ID 有错误');}

view.php 中是模态元素

<?= Html::button('添加合奏人员',['价值' =>Url::to(['ensemble/add', 'id' => $model->id]),'标题' =>'增加新的合奏人员','类' =>'showModalButton btn btn-primary']);?></p><?php模态::开始(['关闭按钮' =>['标签' =>'X',],'headerOptions' =>['id' =>'modalHeader'],'id' =>'模态','尺寸' =>'模态-lg',]);echo "<div id='modalContent'></div>";模态::结束();?>

触发一切的 js 代码...

$(function(){$(document).on('click', '.showModalButton', function(){if ($('#modal').data('bs.modal').isShown {$('#modal').find('#modalContent').load($(this).attr('value'));} 别的 {//如果模态没有打开;打开它并加载内容$('#modal').modal('show').find('#modalContent').load($(this).attr('value'));}//动态设置模态标题...});});

以及处理 add 动作的 ensemble 控制器

公共函数 actionAdd($id){$model = $this->findModel($id);//在帖子中 ('ensembleStaff_ids' => [0 => '2']);其中 id 实际上是 staff_idif ($model->load(Yii::$app->request->post()) && $model->save()) {返回 $this->redirect(['view', 'id' => $id]);} 别的 {return $this->renderAjax('add', ['模型' =>$模型,]);}}

以及js注入模型的表单(Url::to(['ensemble/add', 'id' => $model->id]),)

<?php $form = ActiveForm::begin(['id' => 'add-theater-stuff-form']);?><?= $form->field($model, 'staff_ids')->widget(Select2::className(), ['模型' =>$模型,'数据' =>ArrayHelper::map(app\models\TheaterStaff::find()->where(['theater_id' => $model->theater_id])->all(), 'staff_id', 'staff.fullname'),'选项' =>['多个' =>真的,'提示' =>'合奏人员',],'插件选项' =>['标签' =>真的]]);?><div class="form-group"><?= Html::submitButton('Add', ['class' =>'btn btn-primary']) ?>

<?php ActiveForm::end();?>

点击 Add Ensemble Staff 按钮工作正常并调出模态窗口.到目前为止,表单本身运行良好;默认验证也有效.即使调用了自定义验证,但 return $this->renderAjax(...) 不再加载到模态窗口中;是分开的.

A 图片 显示加载的模态、提交后的结果和带有默认验证.

我在此处发现了类似的问题.但是在表单中添加一个 id 并不能解决问题.那么如何让默认验证正确显示在模态窗口中呢?有人知道吗?

解决方案

感谢您的回复.对我来说,解决方案是:在表单中启用ajax

 'add-ensemble-stuff-form', 'enableAjaxValidation' => true]);?>

并在控制器中添加以下逻辑

公共函数 actionAdd($id){$model = $this->findModel($id);if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {Yii::$app->response->format = Response::FORMAT_JSON;返回 ActiveForm::validate($model);} 别的 {//在帖子中 ('ensembleStaff_ids' => [0 => '2']);其中 id 实际上是 staff_idif ($model->load(Yii::$app->request->post()) && $model->save()) {返回 $this->redirect(['view', 'id' => $id]);} 别的 {return $this->renderAjax('add', ['模型' =>$模型,]);}}}

解决方案

if (Yii::$app->request->isAjax && $model->load(Yii::$应用程序->请求->post())) {Yii::$app->response->format = Response::FORMAT_JSON;返回 ActiveForm::validate($model);}else{/* 你的代码 */}

在控制器中添加这个use yii\web\Response

I have a model with a custom validation method. For testing it always returns an error message.

public function rules()
{
    return [
     ...
        ['staff_ids', 'each', 'rule' =>  ['string']],
        [['staff_ids'], 'validateStaffIds'],
     ...
    ];
}

public function validateStaffIds($attribute, $params, $validator) {
    $this->addError($attribute, 'There is an error in the staff ids');
}

In the view.php is the modal element

<p>      
    <?= Html::button('Add Ensemble Staff',
            ['value' => Url::to(['ensemble/add', 'id' => $model->id]), 
             'title' => 'Adding New Ensemble Staff',
             'class' => 'showModalButton btn btn-primary']); 
    ?>
</p>

<?php
    Modal::begin([
        'closeButton' => [
              'label' => 'x',
        ],
        'headerOptions' => ['id' => 'modalHeader'],
        'id' => 'modal',
        'size' => 'modal-lg',
    ]);
    echo "<div id='modalContent'></div>";
    Modal::end();
?>

The js code which fires everything up...

$(function(){
    $(document).on('click', '.showModalButton', function(){

        if ($('#modal').data('bs.modal').isShown) {
            $('#modal').find('#modalContent')
                    .load($(this).attr('value'));
        } else {
            //if modal isn't open; open it and load content
            $('#modal').modal('show')
                    .find('#modalContent')
                    .load($(this).attr('value'));      
        }

        //dynamiclly set the header for the modal
        ...
    });
});

And the ensemble controller which handles the add action

public function actionAdd($id)
{
    $model = $this->findModel($id);

    // in the post ( 'ensembleStaff_ids' => [0 => '2']); where the id actually is staff_id
    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['view', 'id' =>  $id]);
    } else {
        return $this->renderAjax('add', [
            'model' => $model,
        ]);
    }
}

And the form which is injected by the js into the model (Url::to(['ensemble/add', 'id' => $model->id]), )

<?php $form = ActiveForm::begin(['id' => 'add-theater-stuff-form']); ?>  

<?= $form->field($model, 'staff_ids')->widget(Select2::className(), [
       'model' => $model,
       'data' => ArrayHelper::map(app\models\TheaterStaff::find()->where(['theater_id' => $model->theater_id])->all(), 'staff_id', 'staff.fullname'),
       'options' => [
           'multiple' => true,
           'prompt' => 'Ensemble Staff',
       ], 
        'pluginOptions' => [
            'tags' => true
        ]
   ]); ?>

<div class="form-group">
    <?= Html::submitButton('Add', ['class' => 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>

Clicking on the Add Ensemble Staff Button works fine and brings up the modal window. The form itself works fine so far; also the default validation works. Even the custom validation is called, but return $this->renderAjax(...) isn't load in the modal window anymore; it is separately.

A picture showing the modal loaded, the result after submit and a modal with default validation.

I found a similar problem here. But adding an id to the form, doesn't solve the problem. So how to get the default validation showing up properly in the modal window? Does anyone have a clue?

Solution

Thanks for the response. For me the solution was: Enable ajax in the form

<?php $form = ActiveForm::begin(['id' => 'add-ensemble-stuff-form', 'enableAjaxValidation' => true]); ?>  

And to add the following logic in the controller

public function actionAdd($id)
    {
        $model = $this->findModel($id);

        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        } else {
            // in the post ( 'ensembleStaff_ids' => [0 => '2']); where the id actually is staff_id
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' =>  $id]);
            } else {
                return $this->renderAjax('add', [
                    'model' => $model,
                ]);
            }
        }
    }

解决方案

if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
    }else{/* your code */}

add this in controller use yii\web\Response

这篇关于Yii2 自定义客户端验证,在模态中使用 ajax 渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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