I want to update my data in GridView using Switch Toogle without refresh the current page.
Here is the image:
So I want to update the attribute status
using the toogle switch like the image above.
Here is my code:
index.php
<?= GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'alumni_id',
'tahun_lulus',
'file_excel',
[
'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,
]);;
}
}
],
//'deleted',
'created_at',
'updated_at',
[ 'class' => 'yii\grid\ActionColumn'],
],
]); ?>
How can I do that with Ajax/Pjax?
Before I suggest you the solution there is something you need to fix as you have redundant code inside the
GridView
that is below.You can just pass the value of the
$data->status
to thevalue
attribute of theSwitchInput
rather than usingif(){}else{}
.Then to implement what you are looking for you have to use the
pluginEvent
option of theSwitchInput
and bind theswitchChange.bootstrapSwitch
event to send an ajax call whenever the status of theSwitchInput
is changed so your code for the Griview should look like belowNote: just make sure you change the
url:'/controller/action',
to the actual URL and action. If you are not usingprettyUrl
then you must change it toindex.php?r=controller/action
.Edit
I have updated the code above to pass the
id
of the row along with thestatus
to your action in the controller, the action will get the variables like below.