Yii2 - Update database field when switchinput widget is clicked

泄露秘密 提交于 2021-02-10 16:00:58

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!