必承其重 | 欲带皇冠 2016-11-19 22:48 采纳率: 0%
浏览 79

Yii2 Activeform Ajax

I have inserted an activeform within each row of a GridView as follows:

Gridview element:

    [
        'content' => function($model) {
            return $this->render('_departmentForm',
                [
                    'model' => $model,
                ]);
        },
    ],

The form:

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(
    ['action' => ['test']]
); ?>

<?= $form
    ->field($model, 'fk_departmentID')
    ->label(false)
    ->dropDownList(
        $model->departments,
        [
            'prompt' => '---- Select Dept ----',
            'onchange' => 'this.form.submit()',
        ]
    ); ?>

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

What I am trying to achieve: When the user changes the dropdown value (i.e. selects a new department for the row), the page should save the new value immediately without refreshing the form.

Unfortunately I don't know what to do next. The form is displaying OK but I don't know how to do an ajax submission.

Thanks!

  • 写回答

1条回答 默认 最新

  • ~Onlooker 2016-11-21 11:58
    关注

    Here is the working solution:

    1. One form (dropdown) per row in gridview
    2. If user changes the dropdown value, the database is immediately updated via ajax without a page reload

    Form: (_departmentForm.php)

    <?php
    use yii\helpers\Html;
    use yii\widgets\ActiveForm;
    
    ?>
    <?php $form = ActiveForm::begin(
        [
            'action' => [
                'survey/department', 
                'question_id' => $model->question_id,
            ],
        ]
    ); ?>
    
    <?= $form
        ->field($model, 'fk_departmentID')
        ->label(false)
        ->dropDownList(
            $model->departments,
            [
                'prompt' => '-- none --',
                'class' => 'form-control ajax-department',
                //'onchange' => 'this.form.submit()', - used for debugging
            ]
        ); ?>
    
    <?php ActiveForm::end(); ?>
    

    GridView:

    <?= GridView::widget([
        'dataProvider' => $questionData,
        'filterModel' => $questionSearch,
        'pager' => [
            'firstPageLabel' => 'First',
            'lastPageLabel' => 'Last',
        ],
        'columns' => [
            //... other fields here
            [
                'content' => function($model) {
                    return $this->render('_departmentForm',
                        [
                            'model' => $model,
                        ]);
                },
            ],
    
        ],
    ]); ?>
    

    JQuery:

    $('.ajax-department').on('change', function () {
        var form = $(this).parent().parent(); // form of the dropdown
        $.ajax({
            url: form.attr('action'),
            type: 'post',
            data: form.serialize(),
            success: function (response) {
                //alert($(response).attr('msg'));
            },
            error: function () {
                alert('Error: There was an error whilst processing this request.');
            }
        });
        return false; 
    });
    

    Controller Action:

    use yii\web\Response;
    
    public function actionDepartment($question_id)
    {
        $model = $this->findModel(['question_id' => $question_id]);
        $post = Yii::$app->request->post();
        Yii::$app->response->format = Response::FORMAT_JSON;
    
        if ($model->load($post) && $model->save()) {
            return ['msg' => 'Successfully updated'];
        } else {
            return ['msg' => 'Update failed'];
        }
    }
    

    That's it - you now have an ajax dropdown within each row of the GridView.

    A couple tips: When debugging the action (server-side activity), comment out the jquery function and uncomment the "onchange" parameter in the form. This causes the form to submit on change and allows you to debug the action. Once your action is working, you can comment out the "onchange" action.

    When debugging the client-side (jQuery) use console.log(...) or alert(...)

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。