首页 > 解决方案 > Yii2 - 使用 Ajax 以模态保存表单

问题描述

我有两种型号,一种是“注册产品”(我有一个包含所有品牌的下拉菜单),另一种是“品牌”。我需要在“注册产品”表单中渲染表单“品牌”以使用引导Modal寡妇创建一个新品牌并且它可以工作,但我需要新创建的品牌在表单的下拉列表中可用,register-products这样我就不会每次都要刷新页面。

此时发生的情况是,在创建新品牌后,正在重定向到包含新品牌细节的视图。

注册产品表格

<?php
 Modal::begin([
     'header' => 'Test',
     'id' => 'modal',
     'size' => 'modal-lg',
 ]);
      echo "<div id='modalContent'></div>";
 Modal::end();
 ?>

Html::a('+', ['/brands/create'], ['id' => 'open_modal', 'class' => 'btn btn-success']);

js

$(function(){
$('#open_modal').click(function (){
    $.get($(this).attr('href'), function(data) {
      $('#modal').modal('show').find('#modalContent').html(data)
   });
   return false;
});

品牌控制器

public function actionCreate()
{
    $model = new Brands();

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['view', 'id' => $model->id]);
    } elseif (Yii::$app->request->isAjax) {
        return $this->renderAjax('create', [
            'model' => $model
        ]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

标签: phpajaxyii2ajaxformpjax

解决方案


推荐阅读