yii2加载一个将表单内容转换为模态的视图

时间:2016-08-16 15:25:47

标签: php jquery modal-dialog yii2

我正在加载一个视图,该视图是控制器操作的结果:

public function actionCreate()
{
    $modelCreate = new CreateForm();
    $user = User::findOne(Yii::$app->user->id);
    $postes = $this->postes($user);


    if (Yii::$app->request->isAjax && $modelCreate->load(Yii::$app->request->post())) {
        Yii::$app->response->format = Response::FORMAT_JSON;
        return ActiveForm::validate($modelCreate);
    }
    if ($modelCreate->load(Yii::$app->request->post()) && Yii::$app->request->isPost){
        $modelCreate->photo = UploadedFile::getInstance($modelCreate, 'photo');
        if ($modelCreate->create()){
            return $this->redirect(['site/view-accounts']);
        }
    }
    return $this->renderAjax('create-account', ['modelCreate' => $modelCreate, 'postes' => $postes]);
}

这是我加载视图的脚本:

$(function(){
    $('#createModal').click(function(){
        $('#newAccountModal').modal('show')
            .find('#modalContentCreate')
            .load($(this).attr('value'));
    });
});

这是我模态的代码:

<?php
    Modal::begin([
        'id' => 'newAccountModal',
        'header' => '<h4>create account</h4>',
    ]);
?>
    <div id ="modalContentCreate">

    </div>
<?php Modal::end();?>

但它会在表单标记之后插入所有脚本,然后触发错误:the xmlHttpRequest object is deprecated ...

表单验证的另一个脚本没有插入主页正文的末尾。

如何触发表单验证并删除此错误消息?

1 个答案:

答案 0 :(得分:1)

要将内容加载到表单中,我建议使用Pjax作为模式的内容,例如:

<?php
    Modal::begin([
        'id' => 'newAccountModal',
        'header' => '<h4>create account</h4>',
    ]);
?>
    <div id ="modalContentCreate">

    <? \yii\widgets\Pjax::begin(['id' => 'pjax1', 'linkSelector' => 'a.my-pjax']) ?>
    <?= $this->render('_form', ['model' => $model]) ?>
    <? \yii\widgets\Pjax::end() ?>

    </div>
<?php Modal::end();?>

包含的表单必须设置data-pjax选项。 请注意Pjax小部件的linkSelector。您可以使用链接替换模态的内容:

<?= \yii\helpers\Html::a('create account', ['account/create'], ['class' => 'my-pjax']) ?>

您的控制器操作'account / create'应处理您的帖子和验证并返回

_form.php(查看)

<? $form = \yii\widgets\ActiveForm::begin(['options' => ['data-pjax' => 1], 'action' => ['account/create']]) ?>    
<?= $form->errorSummary($model) ?>
<?= $form->field($model, 'title') ?>
<?= \yii\helpers\Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
<? \yii\widgets\ActiveForm::end() ?>    

controller create action:

public function actionCreate()
{
    $model = new \common\models\Account;
    if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post()) && $model->validate()) {
        // $model->save()
        return $this->renderAjax('_view', ['model' => $model]);
    }
    return $this->renderAjax('_form', ['model' => $model]);
}

阅读文档:http://www.yiiframework.com/doc-2.0/guide-input-forms.html#working-with-pjax