2016-08-16 65 views
0

我加載一個視圖是控制器作用的結果: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

我不明白你的頭銜。 – zhon

回答

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']) ?> 

控制器行動「帳戶/創建」應該處理您的文章和驗證,並返回


_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]); 
} 

讀取DOC:http://www.yiiframework.com/doc-2.0/guide-input-forms.html#working-with-pjax

+0

如何上傳文件並使用該方法提交? –

+0

此方法更改URL,如果用戶關閉模式並刷新頁面,應該怎麼辦? –

+0

您可以禁用Pjax的$ enablePushState。 http://www.yiiframework.com/doc-2.0/yii-widgets-pjax.html#$enablePushState-detail –