Yii2 SwitchInput widget turns checkboxes and radio buttons into toggle switchinputes

Overview

yii2-widget-switchinput

Latest Stable Version License Total Downloads Monthly Downloads Daily Downloads

The SwitchInput widget turns checkboxes and radio buttons into toggle switchinputes. The plugin is a wrapper for the Bootstrap Switch Plugin and is specially styled for Bootstrap 3.

NOTE: This extension is a sub repo split of yii2-widgets. The split has been done since 08-Nov-2014 to allow developers to install this specific widget in isolation if needed. One can also use the extension the previous way with the whole suite of yii2-widgets.

Installation

The preferred way to install this extension is through composer. Check the composer.json for this extension's requirements and dependencies. Read this web tip /wiki on setting the minimum-stability settings for your application's composer.json.

To install, either run

$ php composer.phar require kartik-v/yii2-widget-switchinput "*"

or add

"kartik-v/yii2-widget-switchinput": "*"

to the require section of your composer.json file.

Latest Release

NOTE: The latest version of the module is v1.3.0 released on 14-Jan-2015. Refer the CHANGE LOG for details.

Demo

You can refer detailed documentation and demos on usage of the extension.

Usage

use kartik\switchinput\SwitchInput;

// Usage with ActiveForm and model
echo $form->field($model, 'status')->widget(SwitchInput::classname(), [
    'type' => SwitchInput::CHECKBOX
]);


// With model & without ActiveForm
echo SwitchInput::widget([
    'name' => 'status_1',
    'type' => SwitchInput::RADIO
]);

License

yii2-widget-switchinput is released under the BSD 3-Clause License. See the bundled LICENSE.md for details.

Comments
  • This widget only support  model?

    This widget only support model?

    This widget only support model? I want use checkbox without model,but the status of checked is associated with options's config value,so when post to form ,it can not post right value,why designed this? in kartik\base\IputWidget.php :

    protected function getInput($type, $list = false)
        {
           //if has model
            if ($this->hasModel()) {
                $input = 'active' . ucfirst($type);
                return $list ?
                    Html::$input($this->model, $this->attribute, $this->data, $this->options) :
                    Html::$input($this->model, $this->attribute, $this->options);
            }
         // if there no model
            $input = $type;
            $checked = false;
            if ($type == 'radio' || $type == 'checkbox') {//the radio tyep do not used this function ,only checkbox use 
                $this->options['value'] = $this->value;
                $checked = ArrayHelper::remove($this->options, 'checked', '');
                if (empty($checked) && !empty($this->value)) {
                    $checked = ($this->value == 0) ? false : true;//why checked status definde by $this->value
                } elseif (empty($checked)) {
                    $checked = false;
                }
            }
            return $list ?
                Html::$input($this->name, $this->value, $this->data, $this->options) :
                (($type == 'checkbox' || $type == 'radio') ?
                    Html::$input($this->name, $checked, $this->options) :
                    Html::$input($this->name, $this->value, $this->options));
        }
    

    I want to do like this without model :

     $tag = SwitchInput::widget([
                        'name' => $name,
                        'value' => 1,//default 1
                        'options' => ['uncheck' => 0,'checked'=>$value],//has hidden input,and checked status by db value
                        'pluginOptions' => ['size' => 'small']
                    ]);
    

    if change like blow ,it will work

    protected function getInput($type, $list = false)
        {
           //if has model
            if ($this->hasModel()) {
                $input = 'active' . ucfirst($type);
                return $list ?
                    Html::$input($this->model, $this->attribute, $this->data, $this->options) :
                    Html::$input($this->model, $this->attribute, $this->options);
            }
         // if there no model
            $input = $type;
            $checked = false;
            if ($type == 'radio' || $type == 'checkbox') {
                $this->options['value'] = $this->value;//not necessary,in widget config options value can also work
                $checked = ArrayHelper::remove($this->options, 'checked', '');
               // if (empty($checked) && !empty($this->value)) {
              //      $checked = ($this->value == 0) ? false : true
              //  } else
               if (empty($checked)) {
                    $checked = false;
                }
            }
            return $list ?
                Html::$input($this->name, $this->value, $this->data, $this->options) :
                (($type == 'checkbox' || $type == 'radio') ?
                    Html::$input($this->name, $checked, $this->options) :
                    Html::$input($this->name, $this->value, $this->options));
        }
    

    .How to resove it?

    enhancement 
    opened by nadirvishun 13
  • width issue

    width issue

    sometimes the switch input width does not fully expand , it is very small. A page refresh will fix, but the issue come up very often.

    switch-input

    <?= $form->field($model, 'is_billable', [ 'options' => ['class' => 'col-md-2']])
    ->widget(SwitchInput::classname(), [
          'type' => SwitchInput::CHECKBOX,
           'pluginOptions' => [
                'size' => 'large',
                 'onColor' => 'success',
                 'offColor' => 'danger',
           ]
    ]); ?>
    
    
    opened by michaelnguyen2021 10
  • Render problem with ajax loaded content

    Render problem with ajax loaded content

    I have a form whose html content changes when the value of a specific dropdown changes. The new html content that contains a couple of switchinput widgets is loaded with ajax and injected in the form. The problem is that the widgets are not rendered but checkboxes are shown instead. If i then save the state of the form and reload the page, the widgets are rendered correctly.

    opened by infoweb-internet-solutions 7
  • switchinput  inside collapse widget

    switchinput inside collapse widget

    When using the switchinput inside a collapse widget the switch does not get initialised with the model value. On submitting the form the value does not get saved.

    echo yii\bootstrap\Collapse::widget([
      'items' => [
        [
          'label'   => 'test',
          'content' => $form->field($model, "[5]value")
            ->widget(kartik\widgets\SwitchInput::className())
            ->label($model->name),
        ]
      ]
    ]);
    

    when i use the same code without a collapse widget there is no problem.

    On inspecting the code i can see there is a hidden field (with the correct value) and an input type checkbox with the wrong value

    question 
    opened by diesonne 4
  • Is there `checked` state?

    Is there `checked` state?

    Hello! Thank you for the very useful widget.

    I'm trying to use it and got an issue. Widget always loading in YES state.

    If attribute value = 0 switch is loading in YES position. If you want to update attribute to value = 1 you must click on switch (it will be changed to NO position) and then click on it again (it will be changed back to YES position). Only after that new value will be assigned.

    // Note: I've looked the code and haven't found any checked state checks in it. It looks like such functionality exists in similar widget: https://github.com/2amigos/yii2-switch-widget

    I've tried 'pluginOptions' => [ 'state' => false ] but it isn't helping too.

    And here is my code from DetailView widget:

    [
        'attribute' => 'yes',
        'format' => 'raw',
        'type'=>DetailView::INPUT_SWITCH,
        'widgetOptions'=>[
            'pluginOptions'=>[
                'state' => false,
                'onText'=>'Yes',
                'offText'=>'No',
                'onColor' => 'success',
                'offColor' => 'danger',
            ]
        ],
        'value'=>$model->active ?
            '<span class="label label-success">Yes</span>' :
            '<span class="label label-danger">No</span>',
    ],  
    
    bug 
    opened by antonkomarev 4
  • SwitchInput in modal

    SwitchInput in modal

    Hi, when i add Switchinput in modal, which is loaded by renderAjax - it's broken like photo below. Sometimes it work fine, but generally it's borken.

    zrzut ekranu z 2017-02-22 10-27-35

    opened by bzajacc 3
  • Not possible to change labelText for radio switch

    Not possible to change labelText for radio switch

    The pluginOptions - labelText does not work correctly when using the radio switchtype.

    The parameter 'pluginOptions' => [ 'labelText' => '',

    is only applicable for the checkbox-type switch. Would be good to be able to have separate image for each radio-switch.

    question 
    opened by jones6951 3
  • disabled save wrong value

    disabled save wrong value

    I'm using the switchinput as follows

    	$form->field($model, 'Active',
    	[
    		'inputOptions' => [
    			'value' => Yii::$app->formatter->asInteger($model->Active), 
    			'class' => 'form-control',
    		],
    		'labelOptions' => ['class' => 'control-label'],
    		'horizontalCssClasses' => [
    			'class' => '',
    			'wrapper' => '',
    		],
    		'template' => '<div class="col-sm-2">{label}</div><div class="col-sm-4">{input}{error}</div>',
    	])
    	->widget(SwitchInput::classname(), 
    	[
    		'options'=>[
    			'tabIndex'=>'345',
    		],
    		'pluginOptions' => [
    			'size' => 'small',
    			'onText' => 'Yes',
    			'offText' => 'No',
    			'onColor' => 'success',
    			'offColor' => 'danger',
    		],
    		'disabled' => (Yii::$app->user->can('Administrator') ? false : true),
    	])
    

    If the use is Administrator, everything works just fine, but, if not, then when the form loads, it displays the value correctly, but always saves all values as No/0, even if it was displaying Yes/1.

    My workaround has been to add javascript before submit to enable all controls.

    opened by DPineault 2
  • Possible to change value even if disabled

    Possible to change value even if disabled

    I used the option options->disabled of the widget to not allow the user changing the value in certain conditions:

    <?= $form->field($model, 'tipo')->widget(Select2::classname(), [
                            'data' => TipoZona::all(),
                            'options' => [
                                'placeholder' => Yii::t('app','Seleziona un tipo ...'),
                                'disabled' => true,
                            ],
                            'pluginOptions' => [
                                'allowClear' => true,
                            ],
                        ]) ?>
    

    The box with 'YES' and 'NO' values is correctly disabled but the value can actually be changed by clicking on the field label and the new value gets correctly submitted and saved.

    opened by liviuk2 2
  • AJAX Load Reinitialize Resets All Settings

    AJAX Load Reinitialize Resets All Settings

    Hi Kartik,

    Great plugin. I'm trying to load new switches via AJAX.

    values = $("input[name='place-chooser']").map(function(){
    $(this).bootstrapSwitch(); });

    Resets the switch to default settings. And, I can figure out how to get it to inherit the PHP settings that came over via AJAX. And, I can't figure out any Jquery API against the $(this).bootstrapSwitch() to reconfigure the settings.

    Using this approach from your post here https://github.com/kartik-v/yii2-tabs-x/issues/18... var opts = window[$('#switch-id').attr('data-krajee-bootstrapSwitch')]; $("#switch-id").bootstrapSwitch(opts); // reinitialize switch input doesn't work at all neither did var opts = window[$('#switch-id').attr('data-kv-switch')];

    I've been struggling with this for 24 hours. I'd appreciate any response you can offer.

    There's just no explanation for reinitialize with settings. Or, Jquery settings of a new AJAX loaded switch

    Thanks!

    opened by newscloud 2
  • [Yii 2.0.35, PHP 7.4, SI: 1.3.1] Display issue in Modal

    [Yii 2.0.35, PHP 7.4, SI: 1.3.1] Display issue in Modal

    Maybe just a config issue, but I dotn see the solution..

    With:

    $form->field( $mdlProjekt, $pd->projekt_column_internal )->widget( \kartik\widgets\SwitchInput::class, [
    		        'pluginOptions' => [
    			        'offText' => $pdlv[0]['value'],
    			        'onText' => $pdlv[1]['value'],
    		        ],
    	        ] )->label( false );
    

    I get a cirrupt result - it works, but the position is a bit off.. Worked in PHP 5.6 and Yii 2.0.16.1 (I currently migrate to PHP 7.4):

    pos pos2

    opened by Commifreak 1
  • No difference between Off/Indeterminate

    No difference between Off/Indeterminate

    When using the switch input without a model, even when setting the IndeterminateValue to -1 (or a positive number for that matter), the result does not appear in the post if it is OFF or Indeterminate, meaning there is no way to differentiate between which the user has selected. It only appears when ON.

    Here is my initialization code:

    
    
    echo SwitchInput::widget(["options" => ["id" => "client_{$i}_setting"],
                                        "name" => "Clients[{$oneClientSetting->catalog_id}]",
                                        "value" => $oneClientSetting->type,
                                        "tristate" => true,
                                        "indeterminateValue" => 2,
                                        "pluginOptions" => [
                                            "onText" => "Show",
                                            "onColor" => "success",
                                            "offColor" => "danger",
                                            "offText" => "Hide",
                                        ],
                                       ]);
    

    Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

    opened by chaslain 0
  • 0 and 1 sent together

    0 and 1 sent together

    Hi,

    this is my code

    <?= $form->field( $model, 'status' )->widget( SwitchInput::class, [
    				'type' => SwitchInput::CHECKBOX
                ] ) ?>
    

    If the checkbox is not checked everything is ok, if the checkbox is checked when I click submit in the ActiveForm, 0 and 1 are sent together

    Model[status]: 0
    Model[status]: 1
    

    Regards


    Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

    opened by diego-betto 0
  • Setting checked value on javascript function called

    Setting checked value on javascript function called

    Hi, I am trying to use this widget and it is really useful, I really like it, but I'm facing the following problem: I have an activeForm in wich under certain conditions I call a "populate()" javascript function for filling the form fields, but I can't manage to change the switch to its 'on' property. I am using it as a checkbox in the following way:

    $form->field($model, "es_usuario")->widget(SwitchInput::classname(), [
                                        'pluginOptions' => [
                                            'onText' => 'Sí',
                                            'offText' => 'No',
                                            'onColor' => 'success'
                                        ],
                                    ])->label("Agregar como usuario del sistema?");
    

    I have tried with:
    $('#contactos-es_usuario').val(true); $('#contactos-es_usuario').prop('checked', true); $('#contactos-es_usuario').attr('checked', true); $('#contactos-es_usuario')[0].checked = true; With no results in any of these. When I check the element in the development tools, the checked property does change to true, but the switch remains the same.

    I'd really appreciate give me any help with this. Thanks in advance


    Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

    opened by danisetg 1
  • Class kartik\switchinput\SwitchInput not found

    Class kartik\switchinput\SwitchInput not found

    i am new to yii2, i have integrated this widget as instructed in doc but it i have this error "Class kartik\switchinput\SwitchInput not found". i am using yii2 advanced template and the extension is placed on root vendor folder. where do i fix the path for this extension? please help. Thanks!!!


    Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

    opened by a-M-i-T 2
  • First click/touch of three way toggle usually goes to NO not YES

    First click/touch of three way toggle usually goes to NO not YES

    Is there a way to make the first click of a -1 state 3way toggle go to a particular value?

    I'd like these to go to yes first when people click them rather than no.

    I prefer to have yes on the left rather than no on the left

    Thanks!

    You can see this at SimplePlanner.io . Typically only the participants see the -1 state. So, you'll have to invite another account to a meeting after selecting a time and place.


    Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

    opened by newscloud 0
  • SwitchInput to update database field

    SwitchInput to update database field

    Hello, I am quite new to Yii2. I am trying to use the switchinput widget that when is clicked (on/off) a database field value should change (true/false) to indicate the current state. I think this is done with pluginEvents array and switchChange event:

    echo $form->field($model, 'field1')->widget(SwitchInput::classname(), [
        'type' => SwitchInput::CHECKBOX,
        'name' => 'status_11',
        'pluginOptions' => [
            'size' => 'medium',
            'onColor' => 'success',
            'offColor' => 'danger',
            'onText'=>'YES',
            'offText'=>'NO'
            ],
    'pluginEvents' => [
                'switchChange.bootstrapSwitch' => 'function() { 
                    $.ajax({
                      method: "POST",
                      url: "'.Url::to(['controller/action']).'",
                      data: { xxxxxxxxxxxxxxx}
                  })
                }',
            ],
    

    I want to activate a specific action where the database field is updated. I declare the controller/action in url. I am not sure about the data attribute. Is this the right approach? Any suggestions?


    Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

    opened by gkaltsas 2
Releases(v1.3.1)
  • v1.3.1(Jan 10, 2016)

    Date: 10-Jan-2016

    • (bug #18): Correct typo in documentation and demos.
    • (bug #20): Correct pluginOptions['animate'] initialization.
    • Update to latest release of switch input plugin.
    • Code formatting enhancements and update year.
    Source code(tar.gz)
    Source code(zip)
  • v1.3.0(Jan 22, 2015)

  • v1.2.0(Dec 8, 2014)

    Date: 08-Dec-2014

    • (bug #5): Fix checked state for checkboxes in \kartik\base\InputWidget.
    • (bug #6): Add indeterminate value support and validation for checkboxes
    • (bug #7): Recognize disabled and readonly in pluginOptions automatically
    • (bug #8): Enhanced styling for radio switches and new indeterminate toggle indicator
    • (bug #10, #11 ): Fix missing bracket in code.
    Source code(tar.gz)
    Source code(zip)
  • v1.1.0(Nov 24, 2014)

    Date: 24-Nov-2014

    • (bug #2): Radio does not populate with default value
    • (bug #4): Upgrade to latest release of bootstrap-switch plugin
    • Set release to stable.
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(Nov 9, 2014)

Owner
Kartik Visweswaran
Kartik Visweswaran
An enhanced FileInput widget for Bootstrap 4.x/3.x with file preview, multiple selection, and more features (sub repo split from yii2-widgets)

yii2-widget-fileinput The FileInput widget is a customized file input widget based on Krajee's Bootstrap FileInput JQuery Plugin. The widget enhances

Kartik Visweswaran 227 Nov 6, 2022
Date/Time Picker widget for Yii2 framework Based on Eonasdan's Bootstrap 3 Date/Time Picker

Yii2 Date/Time Picker Widget Date/Time Picker widget for Yii2 framework Based on Eonasdan's Bootstrap 3 Date/Time Picker Demo Since this is a part of

Yevhen Terentiev 8 Mar 14, 2022
An enhanced Yii 2 widget encapsulating the HTML 5 range input (sub repo split from yii2-widgets)

yii2-widget-rangeinput The RangeInput widget is a customized range slider control widget based on HTML5 range input. The widget enhances the default H

Kartik Visweswaran 19 Mar 12, 2022
Simple RBAC Manager for Yii2 (minify of yii2-admin)

Yii2 Mimin Simple RBAC Manager fo Yii 2.0. Minify of yii2-admin extension with awesome features Attention Before you install and use this extension, t

Hafid Mukhlasin 52 Sep 22, 2022
Yii 2 widget for the Froala WYSIWYG HTML Editor.

Yii Framework Froala WYSIWYG HTML Editor Yii 2 widget for Froala Wysiwyg editor. Installation The preferred way to install this extension is through c

Froala 99 Sep 21, 2022
Extends Yii Menu widget

Extends Yii Menu widget. This widget offers a scrollspy and affixed enhanced navigation (upto 2-levels) to highlight sections and secondary sections in each page.

Kartik Visweswaran 15 Mar 12, 2022
DepDrop widget is a Yii 2 wrapper for the dependent-dropdown jQuery plugin by Krajee.

yii2-widget-depdrop The DepDrop widget is a Yii 2 wrapper for the dependent-dropdown jQuery plugin by Krajee. This plugin allows multi level dependent

Kartik Visweswaran 82 Nov 27, 2022
Tarantool connector for yii2 framework. Allow to use activerecord, schemas, widgets and more.

Tarantool connector for yii2 framework Tarantool connector for yii2 framework. Allow to use framework abstractions such as ActiveRecord, Schema, Table

Andrey 11 Nov 21, 2021
A Yii2 module for embedding social plugins and widgets.

yii2-social Module that enables access to social plugins for Yii Framework 2.0. It includes support for embedding plugins from the following networks

Kartik Visweswaran 92 May 29, 2022
Web Push Notifications brought to Yii2

Web Push Notifications for Yii 2 An extension for implementing Web Push Notifications on your website in a breeze. Documentation is at docs/README.md

Mehdi Achour 12 May 19, 2022
yii2-app-advanced with Twitter Bootstrap 5

Yii 2 Advanced Project Template is a skeleton Yii 2 application best for developing complex Web applications with multiple tiers.

Nedarta 1 Nov 5, 2021
Prometheus exporter for Yii2

yii2-prometheus Prometheus Extension for Yii 2 This extension provides a Prometheus exporter component for Yii framework 2.0 applications. This extens

Mehdi Achour 3 Oct 27, 2021
Yii2-symfonymailer - Yii 2 Symfony mailer extension.

Yii Mailer Library - Symfony Mailer Extension This extension provides a Symfony Mailer mail solution for Yii framework 2.0. For license information ch

Yii Software 28 Dec 22, 2022
Yii2 console application used to write our processors of methods to responsible to client calling.

Microservice Application Skeleton Yii2 console application used to write our processors of methods to responsible to client calling. This application

Jafaripur 0 Mar 10, 2022
Yii2 extension for format inputs based on AutoNumeric.js

Yii2 extension for format inputs based on AutoNumeric.js

extead 2 Oct 7, 2019
Pug Yii2 adapter

Yii 2 Pug (ex Jade) extension This extension provides a view renderer for Pug templates for Yii framework 2.0 applications. Support GutHub issues Inst

Pug PHP 8 Jun 17, 2022
This is Yii2 utilities

YII2-UTILITY This is Yii2 utilities. Requirements PHP >= 7.4 Curl extension for PHP7 must be enabled. Download Using Composer From your project direct

null 0 Jun 30, 2022
Alejandro Flores, Php Yii2 Emoac

Prueba Tecnica Emoac Proyecto basado en PHP con Yii2. Hecho por Alejandro Flores, Ingeniero en informática. Este proyecto consta de un CRUD de product

FlamesAlejandro 2 Sep 13, 2022
Easy integration of twitters bootstrap into symfony2

MopaBootstrapBundle MopaBootstrapBundle is a collection of code to integrate twitter's bootstrap (http://twitter.github.com/bootstrap/) as easy as pos

Philipp A. Mohrenweiser 717 Dec 15, 2022