简体   繁体   English

从yii2中的选定复选框获取数据

[英]Get data from selected checkboxes in yii2

I have a form rawmaterial and in that I've a Gridview with checkboxcolumn and some form fields. 我有一个表单原料,其中有一个带有checkboxcolumn和一些表单字段的Gridview。 I want to get all the fields of the selected rows as array. 我想将所选行的所有字段都作为数组。 I've tried to solve as mentioned here - http://www.yiiframework.com/forum/index.php/topic/53777-gridview-get-selected-colum/ . 我已经尝试解决这里提到的问题-http: //www.yiiframework.com/forum/index.php/topic/53777-gridview-get-selected-colum/ But getting Not Found error. 但是出现“未找到”错误。 Code of index.php index.php代码

<?php

use yii\helpers\Html;
use kartik\grid\GridView;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use frontend\models\Rmtemplate;
use kartik\form\ActiveForm;

/* @var $this yii\web\View */
/* @var $searchModel frontend\modules\rmprod\models\RmtemplateSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Templates';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="rmtemplate-index">
    <?php $form = ActiveForm::begin([
        'id' => 'rmtemplate-index',
        'action' => ['/rmprod/Rmtemplate/processSelected',],
        'method' => 'get',
        'enableClientScript' => false,

    ]); ?>

    <h1><?= Html::encode($this->title) ?></h1>
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'id'=>'mytable',
        'columns' => [
            ['class' => 'kartik\grid\CheckboxColumn'],

            //'id',
            //'productname',
            [
                'attribute'=>'productname',
                'filterType'=>GridView::FILTER_SELECT2,
                'filter'=>ArrayHelper::map(Rmtemplate::find()->orderBy(['productname' => SORT_ASC])->asArray()->all(), 'productname', 'productname'),
                'filterWidgetOptions'=>[
                'pluginOptions'=>['allowClear'=>true],
                                    ],
                'filterInputOptions'=>['placeholder'=>'Charge Name'],
            ],
            'rmname',
            'qty',
            // [
            //  'attribute' => 'unitcost',
            //  'value' => 'unitcost.unitcost',
            // ],
            'cost',

            //['class' => 'kartik\grid\ActionColumn'],
        ],
    ]); ?>
    <div class="form-group pull-right">
        <?= Html::submitButton('Next', ['class' => 'btn btn-primary search','id'=>'tabbutton',]) ?>
    </div>
</div>
<?php ActiveForm::end(); ?>

<?php
/* start getting the data */
$script = <<<EOD
$('tabbutton').one('click',function() {
    var keys = $('#w0').yiiGridView('getSelectedRows'); // returns an array of pkeys, and #grid is your grid element id
    $.post({
       url: '/rmtemplate/processSelected', // your controller action
       dataType: 'json',
       data: {keylist: keys},
       success: function(data) {
          if (data.status === 'success') {
              alert('I did it! Processed checked rows.');
          }
       },
    });
});
EOD;
$this->registerJs($script);
/*end getting the data */
?>

Controller Action 控制器动作

public function actionProcessSelected() {
    if (isset($_POST['keylist'])) {
        $keys = \yii\helpers\Json::decode($_POST['keylist']);
        // you will have the array of pk ids to process in $keys
        // perform batch action on these keys and return status
        // back to ajax call above
        }
    }

Console 安慰 在此处输入图片说明

Output 产量 在此处输入图片说明

Give an id to the GridView like: 为GridView提供一个ID,如下所示:

<?= GridView::widget([
  'id'=>'mytable',
   ...

And in your js code, call this: 在您的js代码中,调用此代码:

var rows = $('#mytable').yiiGridView('getSelectedRows');

There are two possible(Temporary) soutions you can try: Solution 1:: 您可以尝试两种可能的(临时) 解决方案解决方案1:

In Index.php=>  
    //define action  ::  
    $productupdate = '/rmprod/Rmtemplate/processSelected';  
    In column add this........  
    [  
     'class' => 'kartik\grid\CheckboxColumn'  
     'checkboxOptions' => function ($data) {  
               return ['value' =>  $data['product_primary_key'], 'class' => 'class_checkbox'];  //primary_key=>product_primary_key
                        },  
    ],  
    Add Jquery code(To post data) ::::  
        $('.class_checkbox').change(function()  
        {  
            var action_url = '<?= $productupdate; ?>';  
            if (this.checked) {  
                var product_data = $(this).attr('value'); //get product_primary_key  
                $.ajax({  
                    method: "post",  
                    url: action_url,  
                    data: {product_data:product_data,_csrf: csrfToken}  
                }).done(function(data)  
                { 
                    $('#LoadingMSG').hide();  
                    console.log(data);  
                });  
            }
            else  
            {  
                //you can apply another ajax to post data when checkbox unselect  
            }  
        });  
    In Controller=>  
    public function processSelected()  
    {  
    $getdata = Yii::$app->request->post(); //get posted data   
    //apply query to play with database by $getdata (primary_key)  
    }

Solution 2 解决方案2

In Index.php.............  
    [  
     'class' => 'kartik\grid\CheckboxColumn'  
     'checkboxOptions' => function ($data) {  
               return ['value' =>  $value1.'+'.$value2.'+'.$value3.'+'.$value4, 'class' => 'class_checkbox']; 
                        },  
    ],   
    Add Jquery code(To post data) ::::  
        $('.class_checkbox').change(function()  
        {  
            var action_url = '<?= $productupdate; ?>';  
            if (this.checked) {  
                var all_flds_data = $(this).attr('value'); 
                $.ajax({  
                    method: "post",  
                    url: action_url,  
                    data: {all_flds_data:all_flds_data,_csrf: csrfToken}  
                }).done(function(data)  
                { 
                    $('#LoadingMSG').hide();  
                    console.log(data);  
                });  
            }
            else  
            {  
                //you can apply another ajax to post data when checkbox unselect  
            }  
        });  
In Controller=>  
    public function processSelected()  
    {  
    $getdata = Yii::$app->request->post(); //get posted data   
    //after json_deocode you will get all posted data from ajax  
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM