簡體   English   中英

yii2加載一個視圖,該視圖將表單包含在模式中

[英]yii2 load a view that content a form into 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();?>

但是它將所有腳本插入到form標記之后,然后觸發錯誤: the xmlHttpRequest object is deprecated ...

並且表單驗證的其他腳本未插入首頁的末尾。

如何觸發表單驗證並刪除此錯誤消息?

要將內容加載到表單中,我建議使用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選項。 注意linkSelector為Pjax部件。 您可以使用鏈接替換模式內容:

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

您的控制器操作“帳戶/創建”應處理您的帖子和驗證並返回


_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() ?>    

控制器創建動作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM