模态窗口中的Yii2形式

时间:2016-03-19 19:44:29

标签: ajax forms modal-dialog yii2

我想了解如何使用Yii2中的Modal窗口处理表单的基础知识?这是我目前的理解,如果有人能解释我错过了什么,我将不胜感激。 所以,我有一个带有记录的ListView。每条记录都包含一个按钮。该按钮打开一个带有表格的模态:

echo Html::a('<span class="glyphicon glyphicon-bell" aria-hidden="true"></span>', ['#'],[
                         'id' => $model->id,
                         'class' => 'linkbutton',
                         'data-toggle'=>'modal',
                         'data-tooltip'=>'true',
                         'data-target'=>'#submit_vote'.$model->id,
                         'title'=> 'Assign'
                     ]);

                Modal::begin([
                    'size' => 'modal-lg',
                    'options' => [
                        'id' => 'submit_vote'.$model->id,
                    ],
                    'header' => '<h2>Create Vote</h2>',
                    'footer' => 'Footer'
                ]);

                ActiveForm::begin([
                    'action' => 'vote/vote',
                    'method' => 'post',
                    'id' => 'form'.$model->id
                ]);

                echo Html::input(
                        'type: text',
                        'search',
                        '',
                        [
                            'placeholder' => 'Search...',
                            'class' => 'form-control'
                        ]
                );

                echo Html::submitButton(
                        '<span class="glyphicon glyphicon-search"></span>',
                        [
                            'class' => 'btn btn-success',
                        ]
                );
                ActiveForm::End();
                Modal::end();

表格&#39;行动&#39;我写了投票/投票和方法职位。所以我希望在我的VoteController的actionVote函数中发布数据。

public function actionVote()
    {
        if (Yii::$app->request->post()) {
        $id = Yii::$app->request->post('search');
        Yii::$app->session->setFlash('error', $id);
        return true; 
        }
    }

提交我使用ajax:

$('form').on('submit', function () {
    alert($(this).attr('id')+$(this).attr('action')+$(this).serialize());  //just to see what data is coming to js
    if($(this).attr('id') !== 'searchForm') {  //some check
            $.ajax({
            url: $(this).attr('action'),
            type: 'post',
            data: $(this).serialize(),
            success: function(){
                $("#submit_vote15").modal('hide'); //hide popup  
            },
        });  
        return false;
    }

但点击提交表单后,我看到两个警报。莫代尔也没有隐藏。 Flash消息也未显示。 我做错了什么?任何人都可以清楚地解释数据流的一步一步程序吗?现在我的理解是:

  1. Open Modal;
  2. 点击Modal内的表单提交;
  3. 通过ajax将数据加载到控制器操作;
  4. 从post发送数据并执行控制器动作代码; 我错过了什么?

3 个答案:

答案 0 :(得分:9)

您可以按照以下步骤进行操作......

第1步:定义链接按钮,如

<?php echo Html::a('<span class="glyphicon glyphicon-comment"></span>',
                    ['/feed/mycomment','id' => $model->id], 
                    [
                        'title' => 'View Feed Comments',
                        'data-toggle'=>'modal',
                        'data-target'=>'#modalvote',
                    ]
                   );
?>

第2步:定义弹出窗口(远程网址)

<div class="modal remote fade" id="modalvote">
        <div class="modal-dialog">
            <div class="modal-content loader-lg"></div>
        </div>
</div>

第3步:在控制器中定义远程网址操作,如

public function actionMyComment()
{
       $model = new MyComment();
       return $this->renderAjax('_add_comment', [
                'model' => $model,
        ]);

}

第4步:定义您的视图文件_add_comment

<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
?>
    <?php $form = ActiveForm::begin([ 'enableClientValidation' => true,
                'options'                => [
                    'id'      => 'dynamic-form'
                 ]]);
                ?>

      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Add Comment</h4>
      </div>
      <div class="modal-body">
            <?php echo $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
            <?php echo $form->field($model, 'email')->textInput(['maxlength' => true]) ?>
            <?php echo $form->field($model, 'comment')->textArea() ?>
      </div>
      <div class="modal-footer">
       <?php echo Html::submitButton(Yii::t('backend', 'Send'), ['class' => 'btn btn-success']) ?>
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
      <?php ActiveForm::end(); ?>

它的......:)

答案 1 :(得分:1)

我看到一些问题,首先你在提交事件中使用,所以yii一旦事件和浏览器再次触发(这是警报显示两次的原因),你应该使用beforeSubmit事件。其次,消息不会显示,因为您不再渲染它,只需将其设置在控制器中即可。要关闭模态,您应该将代码更改为

$(".modal").modal('hide'); 

有用的链接是this

答案 2 :(得分:0)

此处解决方案 Yii2使用ajax在“模式”弹出窗口中呈现表单

第1步:按钮打开模型

<span  class="hand-cursor-pointer quick-add-contact" title="Add Contact"><i class="fa fa-plus-circle" aria-hidden="true"></i>Add Contact Via Model</span>

第2步:JAVASCRIPT

<?php
$url = Yii::$app->urlManager->createUrl('modulesname/controllername/add-contact');

$script = <<< JS
//QUICK CREARE CONTACT MODEL
$(document).on('click', '.quick-add-contact', function () {       
    $('#addContactFormModel').modal('show').find('.modal-dialog').load('$url');
});

JS;
$this->registerJs($script);
?>

第3步:HTML模型:

<!-- POPUP MODAL CONTACT -->                            
<div class="modal inmodal contact" id="addContactFormModel" role="dialog" data-keyboard="false" data-backdrop="static">
    <div class="modal-dialog modal-md "></div>
</div> 

第4步:控制器

/**
 * Quick Add Contact Action
 * @param type $id
 * @return type
 */
public function actionAddContact() {

    $model = new ContactsManagement();

    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
        $transaction = \Yii::$app->db->beginTransaction();          
        try {
            if ($model->validate()) {
                $flag = $model->save(false);
                if ($flag == true) {
                    $transaction->commit();                      
                    return Json::encode(array('status' => 'success', 'type' => 'success', 'message' => 'Contact created successfully.'));
                } else {
                    $transaction->rollBack();
                }
            } else {
                return Json::encode(array('status' => 'warning', 'type' => 'warning', 'message' => 'Contact can not created.'));
            }
        } catch (Exception $ex) {
            $transaction->rollBack();
        }
    }

    return $this->renderAjax('_add_form', [
                'model' => $model,
    ]);
}

/*
 * QUICK CREATE CONTACT FORM VALIDATION
 */

public function actionContactValidate() {
    $model = new ContactsManagement();
    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
        $model->company_id = Yii::$app->user->identity->company_id;
        $model->created_at = time();
        \Yii::$app->response->format = Response::FORMAT_JSON;
        return ActiveForm::validate($model);
    }
}

第5步:查看文件

<div class="modal-content animated bounceInTop" >
    <?php
    $form = ActiveForm::begin(['id' => 'form-add-contact', 'enableAjaxValidation' => true, 'validationUrl' => Yii::$app->urlManager->createUrl('contacts/contacts/contact-validate')]);
    ?>
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title text-left">Add Contact</h4>
    </div>
    <div class="modal-body">       
        <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
        <?= $form->field($model, 'emailid')->textInput(['maxlength' => true]) ?>
        <?= $form->field($model, 'mobile')->textInput(['maxlength' => true]) ?>
        <div class=" view-btn text-left"> 
            <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-default' : 'btn btn-default']) ?>
            <button  type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
        </div>
    </div>
    <?php ActiveForm::end(); ?>
</div>

<?php
$script = <<< JS

   $(document).ready(function () { 
        $("#form-add-contact").on('beforeSubmit', function (event) { 
            event.preventDefault();            
            var form_data = new FormData($('#form-add-contact')[0]);
            $.ajax({
                   url: $("#form-add-contact").attr('action'), 
                   dataType: 'JSON',  
                   cache: false,
                   contentType: false,
                   processData: false,
                   data: form_data, //$(this).serialize(),                      
                   type: 'post',                        
                   beforeSend: function() {
                   },
                   success: function(response){                      
                       toastr.success("",response.message); 
                       $('#addContactFormModel').modal('hide');
                   },
                   complete: function() {
                   },
                   error: function (data) {
                      toastr.warning("","There may a error on uploading. Try again later");    
                   }
                });                
            return false;
        });
    });       

JS;
$this->registerJs($script);
?>