Что происходит за кулисами, когда я нажимаю на флажок столбца флажок Yii2 GridView::widget?

Используйте следующую функцию контроллера для захвата сгенерированного javascript массива 'keylist', когда вы устанавливаете флажок под столбцом флажка Yii2 в gridview.

Ошибка, которую я совершил: не осознавая, что действие Doit запускалось за кулисами каждый раз, когда я нажимал на флажок.

Просмотрите журнал на панели инструментов отладчика Yii, нажав на красную кнопку ajax alert слева.

Нажмите на ссылку профиля для POST 404, чтобы получить преднамеренный журнал ошибок.

public function actionDoit()
{
  //1.  Deliberately throw an exception to catch the following
  //    getKeys javascript which I created under scripts.js and 
  //    saved under D:\wamp\www\advanced\web\frontend\web\js
  /*
        function getKeys(){
            var keys = $('#w1').yiiGridView('getSelectedRows'); 
            $.post({  url: "/product/doit",
                 dataType: "json",
                     data: {keylist: keys},
            //Uncomment the following line to verify getKeys function is being run when clicking on checkboxcolumn 
               //success: alert(keys)
        });}

        This can be seen in small ajax redbox alert in the Yii debugger tool (installed by default) on the toolbar. Click on far right <  
        to have the debugger tool present.
        Look for ajax red alert box on far left of toolbar when checkbox is clicked. (not form button is clicked)
   */ 
   //2. Did not use .... var keys = $('#grid').yiiGridView('getSelectedRows'); 
   //   Instead I used .... var keys = $('#w1').yiiGridView('getSelectedRows'); 

   //3. The following code appears in my gridview.
   /*
    * <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        ['class' => 'yii\grid\CheckboxColumn',
        //the name of checkbox's under the checkboxcolumn. Not to be confused with 'keylist'.
        //They appear with [] appended to selection.
        'name'=>'selection',
        'multiple'=>true,
        'checkboxOptions'=>function ($model, $key, $index){
            return ['id'=>"{$model->id}", 'onclick'=>'js:getKeys()' ,'value' => $model->name];
        }
    */ 
    // 4. Look for a POST 404 red alert by clicking on the ajax alert box on far left of Yii debugger toolbar.
    // 5. If you see something like the following....
    //    13:27:54.723 error yii\web\HttpException:404 yii\web\NotFoundHttpException: Here 9 and request is is arrayAJAXPOST in D:\wamp29 
    // 6. ....your 'doit' controller action function has successfully been run EACH TIME YOU CLICKED on a  checkbox. 
    // 7. ....NOTE: No button was clicked. All the clicked checkbox values are sent to the controller when you click a checkbox.
    // 8. ....This can be verified by uncommenting //success: alert(keys);
    // 9. ....It made no difference changing $.post with $.ajax under the script.

   if (isset($_POST['keylist']))
   {
       //Equivalent to: $arr=$_POST['keylist'];
       $request = Yii::$app->request;
       $arr = $request->post('keylist');

       //Unnecessary: $keys = \yii\helpers\Json::decode($params,true);

       //Extract the array $arr into individual keys separated by a comma,
       $keys = implode(",",$arr);

       if (is_array($arr)) {$message = "is array ";}
       if ($request->isAjax) { $message .= "AJAX "; }
       if ($request->isPost) { $message .= "POST "; }
       throw new NotFoundHttpException('Here '.$keys.' and request is '.$message);
    }

}

0 ответов

Другие вопросы по тегам