问题
I am using the switchinput Kartik widget which I have related to a database true/false field (field1). What I want to do is to be able to update this database field value when I change the switch.
Here is the view code:
<?php
echo $form->field($model, 'field1')->widget(SwitchInput::classname(), [
'type' => SwitchInput::CHECKBOX,
'name' => 'status_11',
'pluginOptions' => [
'size' => 'medium',
'onColor' => 'success',
'offColor' => 'danger',
'handleWidth'=>80,
'onText'=>'ACTIVE',
'offText'=>'INACTIVE'
]
]);
?>
and here is the controller code that tries to update the database:
.................
if (isset($_POST['status_11']))
{
if ($model->field1 == False)
{
$model->field1 = True;
}
else
{
$model->field1 = False;
}
}
if(!$model->save())
{
throw new Exception('Could not save to database. Trnasaction aborted.');
}
..................
The switch can read from the database the value of field1 and show on or off respectively. But the change (onclick) action does not update the database...
Should I try using PHP or should I implement it with js ('pluginEvents' widget option) and how? Any suggestions would be highly appreciated. Thank you in advance.
回答1:
You should use the pluginEvents
array with the switchChange
event, to trigger an ajax call to your php script, which updates the database:
pluginEvents = [
"switchChange.bootstrapSwitch" => 'function() {
$.ajax({
method: "POST",
url: "'.Url::to(['/controller/action']).'",
data: { status_11: state}
})
}',
];
来源:https://stackoverflow.com/questions/43064400/yii2-update-database-field-when-switchinput-widget-is-clicked