Yii2-在gridview中使用多个复选框 [英] Yii2-Working with multiple check boxes in gridview

查看:34
本文介绍了Yii2-在gridview中使用多个复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 gridview,其中还有一个复选框.

 <?= Html::a('Disconnect', ['dco'], ['class' => 'btn btn-success', 'id'=>'dco'])?><?= Html::a('Connect', ['rco'], ['class' => 'btn btn-info','id'=>'rco']) ?><?php Pjax::begin();?><div class="pre-scrollable"><?= GridView::widget(['数据提供者' =>$数据提供者,'过滤器模型' =>$搜索模型,'列' =>[['类' =>'yiigridCheckboxColumn', 'checkboxOptions' =>函数($d){返回 ['值' =>$d['msn']];}],'客户ID','部门名称:ntext','sub_div_name','部门名称','allowed_units','msn','units_consumed',['标签' =>'断开','属性' =>'断开','格式'=>'原始','内容选项' =>['style'='text-align:center'],'价值' =>功能($模型){返回 $model->disconnected == 1 ?'<span class="glyphicon glyphicon-ok text-success"></span>': '<span class="glyphicon glyphicon-remove text-danger"></span>';},'过滤器' =>Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' =>'表单控制']),],'active_energy_total_m',['类' =>'yiigridActionColumn'],],]);?>

我正在使用 ajax 将检查的数据发送到控制器.

有两个按钮DisconnectConnect.在勾选的复选框上,点击两个按钮中的任意一个后,对应的选中项将被连接或断开.

$DCOurl = Url::toRoute(['/hescolog/dco']);$RCOurl = Url::toRoute(['/hescolog/rco']);$(document).ready(function () {//数据中心$('#dco').on('click',function(e) {e.preventDefault();var strValue = "";$('input[name="selection[]"]:checked').each(function() {if(strValue!==""){strValue = strValue + " , " + this.value;}别的strValue = this.value;});//警报(strValue);$.ajax({url: '$DCOurl',类型:'POST',数据类型:'json',数据:{数据:strValue},成功:功能(数据){警报(数据);}});});$('#rco').on('click',function(e) {e.preventDefault();var strValue = "";$('input[name="selection[]"]:checked').each(function() {if(strValue!==""){strValue = strValue + " , " + this.value;}别的strValue = this.value;});//警报(strValue);$.ajax({url: '$RCOurl',类型:'POST',数据类型:'json',数据:{数据:strValue},成功:功能(数据){警报(数据);}});});});

控制器

if(Yii::$app->request->isAjax && Yii::$app->request->post()){$data =explode(',',$_POST['data']);foreach($data 作为 $value){//...... 其他代码}}

现在我面临的问题是当我选中所有复选框并单击任何按钮时,只有第一个复选框选中了一个项目是连接或断开连接.

虽然在检查控制器时``我可以看到检查复选框的两个项目.

array(2) { [0]=>字符串(13)002995000100"[1]=>字符串(13)002992002018"}

更新 1

针对这两个按钮,我有一个 SOAP 服务

 if(Yii::$app->request->isAjax && Yii::$app->request->isPost){$data =explode(',',$_POST['data']);foreach($data 作为 $value){$ic++;$msn = $value;$xml_post_string =/** @lang text */'<soapenv:信封xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"xmlns:soap="http://soap.inf.hexing.cn"><soapenv:Header/><soapenv:Body><soap:doCommand><!--可选:--><arg0><![CDATA[<?xml version="1.0" encoding="utf-8"?><请求消息xmlns="http://iec.ch/TC57/2011/schema/message"xmlns:m="http://iec.ch/TC57/2011/EndDeviceControls#"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://iec.ch/TC57/2011/schema/message消息.xsd"><标题><动词>创建</动词><名词>EndDeviceControls</名词><修订版>2.0</修订版><时间戳>2016-01-01T00:00:00+04:30</时间戳><来源>MDM</来源><AsyncReplyFlag>true</AsyncReplyFlag><回复地址>http://ip:port/AmiWeb/services/Metering</ReplyAddress><AckRequired>true</AckRequired><用户><UserID>'.$userName.'</UserID></用户><MessageID>83c643e6-85c5-43c0-9e0a-fa1deb469b72</MessageID><CorrelationID>1001</CorrelationID><财产><姓名>密码</姓名><值>'.$password.'</值></属性><财产><名称>超时(m)</名称><值>30</值></属性></标题><有效载荷><m:EndDeviceControls><m:EndDeviceControl><m:reason>断开/重新连接</m:reason><m:EndDeviceControlType ref="3.0.211.23"/><m:终端设备><m:mRID>'.$msn.'</m:mRID><m:名字><m:name>断开连接</m:name><m:name>ControlType</m:name></m:NameType></m:姓名></m:EndDevices></m:EndDeviceControl></m:EndDeviceControls></有效载荷></RequestMessage>]]></soap:doCommand></soapenv:Body></soapenv:Envelope>';$headers = 数组("内容类型: text/xml;charset="utf-8"","接受:文本/xml","缓存控制:无缓存","pragma: no-cache","内容长度:".strlen($xml_post_string),);//SOAPAction: 你的操作 URL$url = $soapUrl;//用于 https 连接的 PHP cURL$ch = curl_init();curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword);//用户名和密码 - 在文档顶部声明curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);curl_setopt($ch, CURLOPT_TIMEOUT, 10);curl_setopt($ch, CURLOPT_POST, true);curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string);//SOAP 请求curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);//转换$response = curl_exec($ch);curl_close($ch);$domd=new DOMDocument();if(!$domd->loadXML($response)){throw new RuntimeException("解析 XML 失败!");}$inner_xml=$domd->getElementsByTagName("return")->item(0)->textContent;if(!($domd2=@DOMDocument::loadXML($inner_xml))){throw new RuntimeException("解析inner_xml失败!");}$AsyncReplyFlag=$domd2->getElementsByTagName("AsyncReplyFlag")->item(0)->textContent;if ($AsyncReplyFlag =='true'){$ds = 1;$disconnected_at = date('Y-m-d H:i:s');尝试 {Yii::$app->db->createCommand(/** @lang text */更新`accurate_mam`.`daily_log`放`断开连接` = '$ds',`diconnected_at` = '$disconnected_at',`reconnected_at` = NULL其中`msn` = '$msn';")->execute();//更新主表Yii::$app->db->createCommand(/** @lang text */更新`accurate_mam`.`log_disconnected`放`disconnected_at` = '$disconnected_at'where `msn` = '$msn'")->execute();//更新日志断开表} 捕获(异常 $e){}//更新主表}}}

我不知道是什么问题以及为什么我无法处理这两个记录.

任何帮助将不胜感激.

解决方案

因为你留下了评论 这里,我使用了beginForm方法:

在视图中

<?php Pjax::begin() ?><?=Html::beginForm(['test'],'post');?><?= Html::submitButton('Disconnect', ['class' => 'btn btn-success', 'name'=>'dco', 'value'=>'dco', 'id'=>'dco','style'='margin:0 10px;']) ?><?= Html::submitButton('Connect', ['class' => 'btn btn-primary', 'name'=>'rco', 'value'='rco','id'=>'rco']) ?><?= GridView::widget(['数据提供者' =>$数据提供者,'过滤器模型' =>$搜索模型,'列' =>[['类' =>'yiigridCheckboxColumn', 'checkboxOptions' =>函数($d){返回 ['值' =>$d['msn']];}],'客户ID','部门名称:ntext','sub_div_name','部门名称','allowed_units','msn','units_consumed',['标签' =>'断开','属性' =>'断开','格式'=>'原始','内容选项' =>['style'='text-align:center'],'价值' =>功能($模型){返回 $model->disconnected == 1 ?'<span class="glyphicon glyphicon-ok text-success"></span>': '<span class="glyphicon glyphicon-remove text-danger"></span>';},'过滤器' =>Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' =>'表单控制']),],'active_energy_total_m',['类' =>'yiigridActionColumn'],],]);?><?= Html::endForm();?><?php Pjax::end() ?>

在控制器中

公共函数 actionTest(){$searchModel = Yii::createObject(appmodelsTestSearch::className());$dataProvider = $searchModel->search(Yii::$app->request->queryParams);if ( Yii::$app->request->post() ) {$arr_select=(array)Yii::$app->request->post('selection');//选中项的数组(复选框)$dco=Yii::$app->request->post('dco');//提交按钮断开连接$rco=Yii::$app->request->post('rco');//提交按钮连接如果 ($dco === 'dco') {//此处断开连接的代码($query)//示例:$modelTest::updateAll(['disconnected' => 1], ['msn' => $arr_select]);} elseif ($rco == 'rco') {//此处连接的代码($query)}}返回 $this->render('test', ['数据提供者' =>$数据提供者,'搜索模型' =>$搜索模型,]);}

您可以在控制器中优化您的代码.
当然,我觉得如果用下面的方法更好(一个按钮和...).
您可以轻松决定控制器.

<?= Html::dropDownList('action','',[ 'Connect' =>'Connect','Disconnect' =>'Disconnect'],['prompt' => '请选择','class'=> 'field-black input-sm']) ?><?= Html::submitButton('Apply', ['class' => 'btn btn-success','style'=>'margin:0 10px;']) ?>

你可以把上面的代码代替两个submitButton.然后根据 dropDownList 值决定控制器.像下面这样:
还要加上:, 'data-pjax'=>''

$_action=Yii::$app->request->post('action');//落下$arr_select=(array)Yii::$app->request->post('selection');//选中的项目

I have a gridview in which there also a checkbox.

    <?= Html::a('Disconnect', ['dco'], ['class' => 'btn btn-success', 'id'=>'dco']) ?>
    <?= Html::a('Connect', ['rco'], ['class' => 'btn btn-info','id'=>'rco']) ?>

<?php Pjax::begin(); ?>
        <div class="pre-scrollable">
        <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [


        ['class' => 'yiigridCheckboxColumn', 'checkboxOptions' => function($d) {
            return ['value' => $d['msn']];
        }],


        'customer_id',       
        'dept_name:ntext',
        'sub_div_name',
        'division_name',

        'allowed_units',
        'msn',

        'units_consumed',
        [
            'label' => 'Disconnected',
            'attribute' => 'disconnected',
            'format'=>'raw',
            'contentOptions' => ['style'=>'text-align:center'],
            'value' => function($model){
                return $model->disconnected == 1 ? '<span class="glyphicon glyphicon-ok text-success"></span>' : '<span class="glyphicon glyphicon-remove text-danger"></span>';
            },
            'filter' => Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' => 'form-control']),
        ],


        'active_energy_total_m',


        ['class' => 'yiigridActionColumn'],
    ],
]); ?>
        </div>

I am using ajax for sending checked data to the controller.

There is two buttons Disconnect and Connect. On the checkbox checked and after clicking any of the two buttons, the corresponding selected item will be connected or disconnected.

$DCOurl = Url::toRoute(['/hescolog/dco']);
$RCOurl = Url::toRoute(['/hescolog/rco']);
$(document).ready(function () {      
//DCO 
 $('#dco').on('click',function(e) {


       e.preventDefault();    
 var strValue = "";        
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!=="")
        {
        strValue = strValue + " , " + this.value;

        }
    else 
       strValue = this.value;     

});

   // alert(strValue);
$.ajax({
     url: '$DCOurl',
     type: 'POST',
     dataType: 'json',
     data: {data:strValue},         
     success: function(data) {
        alert(data);
     }
  });

 });

 $('#rco').on('click',function(e) {
e.preventDefault();    
 var strValue = "";        
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!=="")
        {
        strValue = strValue + " , " + this.value;

        }
    else 
       strValue = this.value;     

});
    // alert(strValue);
$.ajax({
     url: '$RCOurl',
     type: 'POST',
     dataType: 'json',
     data: {data:strValue},         
     success: function(data) {
        alert(data);
     }
  });
  });

  });

Controller

if(Yii::$app->request->isAjax && Yii::$app->request->post())
{
   $data = explode(',',$_POST['data']);
   foreach($data as $value)
   {
      //...... other code
   }
}

Now the problem I am facing is when I check all the checkboxes and click on any of the buttons, only the 1st checkbox checked an item is connect or disconnect.

Although while checking the controller `` I can see both the items against checkbox checked.

array(2) { [0]=> string(13) "002995000100 " [1]=> string(13) " 002992002018" }

Update 1

Against these two buttons, I have a SOAP service

 if(Yii::$app->request->isAjax && Yii::$app->request->isPost)
    {
        $data = explode(',',$_POST['data']);


        foreach($data as $value)
        {
            $ic++;
            $msn = $value;

            $xml_post_string = /** @lang text */
                '<soapenv:Envelope 
            xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:soap="http://soap.inf.hexing.cn">
            <soapenv:Header/>
            <soapenv:Body>
            <soap:doCommand>
            <!--Optional:-->
            <arg0><![CDATA[<?xml version="1.0" encoding="utf-8"?>
            <RequestMessage
            xmlns="http://iec.ch/TC57/2011/schema/message"
            xmlns:m="http://iec.ch/TC57/2011/EndDeviceControls#"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://iec.ch/TC57/2011/schema/message 
            Message.xsd">
            <Header>
            <Verb>create</Verb>
            <Noun>EndDeviceControls</Noun>
            <Revision>2.0</Revision>
            <Timestamp>2016-01-01T00:00:00+04:30</Timestamp>
            <Source>MDM</Source>
            <AsyncReplyFlag>true</AsyncReplyFlag>
      <ReplyAddress>http://ip:port/AmiWeb/services/Metering</ReplyAddress>
            <AckRequired>true</AckRequired>
            <User>
            <UserID>'.$userName.'</UserID>
            </User>
            <MessageID>83c643e6-85c5-43c0-9e0a-fa1deb469b72</MessageID>
            <CorrelationID>1001</CorrelationID>
            <Property>
            <Name>password</Name>
            <Value>'.$password.'</Value>
            </Property>
            <Property>
            <Name>timeout(m)</Name>
            <Value>30</Value>
            </Property>
            </Header>
            <Payload>
            <m:EndDeviceControls>
            <m:EndDeviceControl>
            <m:reason>Disconnect/Reconnect</m:reason>
            <m:EndDeviceControlType ref="3.0.211.23"/>
            <m:EndDevices>
            <m:mRID>'.$msn.'</m:mRID>
            <m:Names>
            <m:name>Disconnect</m:name>
            <m:NameType>
            <m:name>ControlType</m:name>
            </m:NameType>
            </m:Names>
            </m:EndDevices>
            </m:EndDeviceControl>
            </m:EndDeviceControls>
            </Payload>
            </RequestMessage>
            ]]></arg0>
            </soap:doCommand>
            </soapenv:Body>
            </soapenv:Envelope>';

            $headers = array(
                "Content-type: text/xml;charset="utf-8"",
                "Accept: text/xml",
                "Cache-Control: no-cache",
                "Pragma: no-cache",
                "Content-length: ".strlen($xml_post_string),
            ); //SOAPAction: your op URL

            $url = $soapUrl;

            // PHP cURL  for https connection

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            //curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

            // converting
            $response = curl_exec($ch);
            curl_close($ch);
            $domd=new DOMDocument();


            if(!$domd->loadXML($response)){
                throw new RuntimeException("failed to parse XML!");
            }
            $inner_xml=$domd->getElementsByTagName("return")->item(0)->textContent;
            if(!($domd2=@DOMDocument::loadXML($inner_xml))){
                throw new RuntimeException("failed to parse inner_xml!");
            }
            $AsyncReplyFlag=$domd2->getElementsByTagName("AsyncReplyFlag")->item(0)->textContent;


            if ($AsyncReplyFlag =='true')
            {
                $ds = 1;

                $disconnected_at = date('Y-m-d H:i:s');

                try {
                    Yii::$app->db->createCommand(/** @lang text */
                        "update 
                     `accurate_mam`.`daily_log` 
                     set
                     `disconnected` = '$ds',
                     `diconnected_at` = '$disconnected_at', 
                     `reconnected_at` = NULL
                      where `msn` = '$msn' ;

                       ")->execute(); //update master table

                    Yii::$app->db->createCommand(/** @lang text */
                        "update 
                    `accurate_mam`.`log_disconnected` 
                    set

                    `disconnected_at` = '$disconnected_at' 
                     where `msn` = '$msn'")->execute();// update log disconnected table
                } catch (Exception $e) {
                } // updating the master table
            }


        }

    }

I don't know what is the issue and why I am not able to process both the records.

Any help would be highly appreciated.

解决方案

Because you left a comment here, I used the beginForm method:

in View

<div class="pre-scrollable">
  <?php Pjax::begin() ?>
  <?=Html::beginForm(['test'],'post');?>

    <?= Html::submitButton('Disconnect', ['class' => 'btn btn-success', 'name'=>'dco', 'value'=>'dco', 'id'=>'dco','style'=>'margin:0 10px;']) ?>
    <?= Html::submitButton('Connect', ['class' => 'btn btn-primary', 'name'=>'rco', 'value'=>'rco','id'=>'rco']) ?>

    <?= GridView::widget([
      'dataProvider' => $dataProvider,
      'filterModel' => $searchModel,
    'columns' => [

        ['class' => 'yiigridCheckboxColumn', 'checkboxOptions' => function($d) {
            return ['value' => $d['msn']];
        }],

        'customer_id',       
        'dept_name:ntext',
        'sub_div_name',
        'division_name',

        'allowed_units',
        'msn',

        'units_consumed',
        [
            'label' => 'Disconnected',
            'attribute' => 'disconnected',
            'format'=>'raw',
            'contentOptions' => ['style'=>'text-align:center'],
            'value' => function($model){
                return $model->disconnected == 1 ? '<span class="glyphicon glyphicon-ok text-success"></span>' : '<span class="glyphicon glyphicon-remove text-danger"></span>';
            },
            'filter' => Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' => 'form-control']),
        ],

        'active_energy_total_m',

        ['class' => 'yiigridActionColumn'],
    ],
]); ?>

  <?= Html::endForm();?> 
  <?php Pjax::end() ?>
</div>

in controllers

public function actionTest()
{
    $searchModel  = Yii::createObject(appmodelsTestSearch::className());
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

  if ( Yii::$app->request->post() ) {

      $arr_select=(array)Yii::$app->request->post('selection');  //An array of selected items (checkbox)
      $dco=Yii::$app->request->post('dco');  // submitButton Disconnect
      $rco=Yii::$app->request->post('rco');  // submitButton Connect

      if ($dco === 'dco') {
           //code for Disconnect here ($query)
           // example:  $modelTest::updateAll(['disconnected' => 1], ['msn' => $arr_select]);
      } elseif ($rco == 'rco') {
           //code for Connect here ($query)
      }

    }

    return $this->render('test', [
        'dataProvider' => $dataProvider,
        'searchModel'  => $searchModel,
    ]);
}

You can optimize your code in the controller.
Of course, I think if you use the following method, it is better (a button and ...).
You can easily decide on the controller.

<?= Html::dropDownList('action','',[ 'Connect' =>'Connect','Disconnect' =>'Disconnect'],['prompt' => 'Please select','class'=> 'field-black input-sm']) ?>
<?= Html::submitButton('Apply', ['class' => 'btn btn-success','style'=>'margin:0 10px;']) ?>

You can place the above code instead of the two submitButton. Then decide on the controller according to the dropDownList value. Like below:
also add:, 'data-pjax'=>''

$_action=Yii::$app->request->post('action'); // dropDown
$arr_select=(array)Yii::$app->request->post('selection'); //selected items 

这篇关于Yii2-在gridview中使用多个复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆