我将加载一个视图,该视图将表单内容放入modal中



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

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

另外一个表单验证脚本没有被插入到主页体的末尾。

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

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

<?php
    Modal::begin([
        'id' => 'newAccountModal',
        'header' => '<h4>create account</h4>',
    ]);
?>
    <div id ="modalContentCreate">
    <? yiiwidgetsPjax::begin(['id' => 'pjax1', 'linkSelector' => 'a.my-pjax']) ?>
    <?= $this->render('_form', ['model' => $model]) ?>
    <? yiiwidgetsPjax::end() ?>
    </div>
<?php Modal::end();?>

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

<?= yiihelpersHtml::a('create account', ['account/create'], ['class' => 'my-pjax']) ?>

你的控制器操作'account/create'应该处理你的post和验证,并返回


_form.php(视图)

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

controller create action:

public function actionCreate()
{
    $model = new commonmodelsAccount;
    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

最新更新