我想使用Switch Toogle在GridView中更新我的数据而不刷新当前页面。这是图像:所以我想使用toogle开关更新属性状态,如上图所示。…
在我建议您解决方案之前,您需要修复一些内容,因为您内部有冗余代码 GridView 在下面。
GridView
[ 'attribute' => 'status', 'format' => 'raw', 'value' => function($data){ if($data->status==0){ return SwitchInput::widget([ 'name' => 'status_11', 'pluginOptions' => [ 'size' => 'mini', 'onColor' => 'success', 'offColor' => 'danger', 'onText' => 'Active', 'offText' => 'Inactive', ], 'value' => true, ]); } else if($data->status==1){ return SwitchInput::widget([ 'name' => 'status_11', 'pluginOptions' => [ 'size' => 'mini', 'onColor' => 'success', 'offColor' => 'danger', 'onText' => 'Active', 'offText' => 'Inactive', ], 'value' => false, ]);; } } ],
你可以传递的价值 $data->status 到了 value 的属性 SwitchInput 而不是使用 if(){}else{} 。
$data->status
value
SwitchInput
if(){}else{}
然后实现你正在寻找的东西你必须使用 pluginEvent 的选择 SwitchInput 绑定 switchChange.bootstrapSwitch 每当状态发送时发送一个ajax调用的事件 SwitchInput 已更改,因此您的Griview代码应如下所示
pluginEvent
switchChange.bootstrapSwitch
<?php use kartik\switchinput\SwitchInput; $js = <<< JS function sendRequest(status, id){ $.ajax({ url:'/controller/action', method:'post', data:{status:status,id:id}, success:function(data){ alert(data); }, error:function(jqXhr,status,error){ alert(error); } }); } JS; $this->registerJs($js, \yii\web\View::POS_READY); echo GridView::widget( [ 'dataProvider' => $dataProvider, //'filterModel' => $searchModel, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], //'alumni_id', 'tahun_lulus', 'file_excel', [ 'attribute' => 'status', 'format' => 'raw', 'value' => function ($data) { return SwitchInput::widget( [ 'name' => 'status_11', 'pluginEvents' => [ 'switchChange.bootstrapSwitch' => "function(e){sendRequest(e.currentTarget.checked, $data->id);}" ], 'pluginOptions' => [ 'size' => 'mini', 'onColor' => 'success', 'offColor' => 'danger', 'onText' => 'Active', 'offText' => 'Inactive' ], 'value' => $data->status ] ); } ], //'deleted', 'created_at', 'updated_at', [ 'class' => 'yii\grid\ActionColumn'], ], ] );
的 注意:只需确保更改 url:'/controller/action', 到实际的URL和动作。如果你不使用 prettyUrl 那你必须改成它 index.php?r=controller/action 。 强>
url:'/controller/action',
prettyUrl
index.php?r=controller/action
我已经更新了上面的代码以通过 id 与行的一起 status 对于你在控制器中的动作,动作将得到如下变量。
id
status
public function actionUpdate(){ $status = Yii::$app->request->post('status'); $id = Yii::$app->request->post('id'); }