Yii2 - 单击 switchinput 小部件时更新数据库字段 [英] Yii2 - Update database field when switchinput widget is clicked

查看:32
本文介绍了Yii2 - 单击 switchinput 小部件时更新数据库字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用与数据库真/假字段 (field1) 相关的 switchinput Kartik 小部件.我想要做的是当我改变开关时能够更新这个数据库字段值.

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.

这是查看代码:

<?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.');
                    }
..................

开关可以从数据库中读取field1的值,分别显示on或off.但是更改(onclick)操作不会更新数据库...

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...

我应该尝试使用 PHP 还是应该使用 js('pluginEvents' 小部件选项)来实现它以及如何实现?任何建议将不胜感激.提前致谢.

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.

推荐答案

您应该将 pluginEvents 数组与 switchChange 事件一起使用,以触发对您的 php 的 ajax 调用更新数据库的脚本:

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}
      })
    }',
];

这篇关于Yii2 - 单击 switchinput 小部件时更新数据库字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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