如何从Yii2中的模态弹出窗口将数据保存到数据库中?

时间:2017-09-10 22:30:27

标签: php yii2 pjax

我有一个简单的视图,它正确地将数据保存到数据库中,但是当我将该视图放入另一个页面的模态弹出框中时,它不会将任何数据保存到数据库中,而模态只是显示。还有什么需要做的才能将数据从弹出窗口保存到数据库中?感谢

这是控制器:

public function actionEditMyPopup()
{
    $model = new MyPopupForm();
    if ($model->load(Yii::$app->request->post()) && $model->validate()) {
        $model->insertEditMyPopup();
        return $this->renderAjax('edit-mypopup', ['model' => $model]);
    } else {
        return $this->renderAjax('edit-mypopup', ['model' => $model]);
    }   
} 

这是弹出窗口的视图:

<?php Pjax::begin(['enablePushState' => false]); ?>

<?php $form = ActiveForm::begin(['id' => 'edit-mypopup-form', 'options' => ['data-pjax' => true],]); ?>

    <?= $form->field($model, 'attribute1') ?>

<div class="form-group">
    <?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'edit-mypopup-button']) ?>
</div>

<?php ActiveForm::end(); ?>
<?php Pjax::end(); ?>

模型具有变量声明和将数据插入数据库的函数insertEditMyPopup()。

<?php
namespace app\models;
use Yii;
use yii\base\Model;
class EditMyPopupForm extends Model
{
    public $attribute1;

    public function rules()
    {
        return [
              [['attribute1'], 'required'],
        ];
    }

    public function insertEditMyPopup()
    {
        //attributes is the name of the table
        $a = new attributes();
        $a->att1 = $this->attribute1;
        $a->save();

    }//end function  
}//end class

1 个答案:

答案 0 :(得分:0)

我通过在js文件中添加以下代码来克服这个问题:

$('body').on("click", "form#edit-mypopup-form", function() {
    var form = $(this);
    if (form.find('.has-error').length) {
      return false;
    }
        $.ajax({
            url: form.attr('action'),
            type: "POST",
            data: form.serialize(),
            success: function(results){

                 $(form).find('.results').html(results); 

            }
        });
         return false;
});
相关问题