DepDrop widget is a Yii 2 wrapper for the dependent-dropdown jQuery plugin by Krajee.

Overview

Krajee Logo
yii2-widget-depdrop
Donate

Stable Version Unstable Version License Total Downloads Monthly Downloads Daily Downloads

The DepDrop widget is a Yii 2 wrapper for the dependent-dropdown jQuery plugin by Krajee. This plugin allows multi level dependent dropdown with nested dependencies. The plugin thus enables to convert normal select inputs to a dependent input field, whose options are derived based on value selected in another input/or a group of inputs. It works both with normal select options and select with optgroups as well.

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-depdrop "@dev"

or add

"kartik-v/yii2-widget-depdrop": "@dev"

to the require section of your composer.json file.

Release Changes

NOTE: Refer the CHANGE LOG for details on changes to various releases.

Demo

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

Usage

use kartik\depdrop\DepDrop;

// Normal parent select
echo $form->field($model, 'cat')->dropDownList($catList, ['id'=>'cat-id']);

// Dependent Dropdown
echo $form->field($model, 'subcat')->widget(DepDrop::classname(), [
     'options' => ['id'=>'subcat-id'],
     'pluginOptions'=>[
         'depends'=>['cat-id'],
         'placeholder' => 'Select...',
         'url' => Url::to(['/site/subcat'])
     ]
 ]);

License

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

Comments
  • [initialize = true] do not work sometimes

    [initialize = true] do not work sometimes

    It work ok most times, but 1-2 times for ~10 tries I have empty value for last selector :( The list is loaded ok and able to select, but value of the field is lost :(

    enhancement 
    opened by aleksanderd 14
  • DepDrop with Pagination or Load More

    DepDrop with Pagination or Load More

    Hello Kartik, Good day. i have been trying to figure out working with DepDrop Yii2 plugin and all is good until i came to a situation where i need to limit the data results returned by the response when the parent dropdown onchange is triggered. I want to DepDrop to behave similarly to the select2 Load more.. / Pagination functionality.

    I dont want to ask any usage question here but not sure if it falls into the category or not, as i could not find anything related to the pagination of the results in the DepDrop documentation.

    SO, a few things i need to ask

    • Firstly is it supported?
    • Do we need to set the pagination var for the ajax call using pluginOptions under select2Options for the DepDrop ? or the pluginOptions for the DepDrop where we specify the ajax url to fetch the data, as for the select2 we need to configure the ajax call using the code
    'ajax' => [
                'url' => $url ,
                'dataType' => 'json' ,
                'data' => new JsExpression ( 'function(params) { return {q:params.term, page:params.page || 1}; }' )
            ] ,
    
    • What should be the response json structure as the normal structure to load data in DepDrop follows the following format
    {
       "out":[
          {
             "id":1,
             "text":"city1"
          },
          {
             "id":2,
             "text":"city2"
          }
       ],
       "selected":1
    }
    

    And looking at the Select2 Docs for Load More / Pagination results, we need to return the results as

    {
       "results":[
          {
             "id":1,
             "text":"Option 1"
          },
          {
             "id":2,
             "text":"Option 2"
          }
       ],
       "pagination":{
          "more":true
       }
    }
    

    Currently, i am initializing the DepDrop with the following options where i am passing the page parameter via params option,

    [
        'id' => 'bill-city',
        'type' => DepDrop::TYPE_SELECT2,
        'pluginOptions' => [
            'placeholder' => 'Select City',
            'depends' => ['state'],
            'url' => Url::to(['/site/cities-list']),
            'params' => ['page'],
        ],
        'options' => [
            'class' => 'form-control',
        ],
    ],
    

    and formatted the results in the same way that Select2 Pagination section expects, on changing the parent Drop-down it does fetches the results correctly but the DepDrop isnt enabled or populated, it statys disabled and no errors on console, which gives me the feeling that the results formatted in this way wont render the options inside the DepDrop.

    How should i go about it if it can be done, if it falls into the usage questions, ignore it but do add a link to the docs where i can follow.

    Thanks.

    opened by buttflattery 8
  • Event issue (depdrop.afterChange)

    Event issue (depdrop.afterChange)

    Hi,

    I would like to thank kartik for his contribution to the community with this great plugin.

    Unfortunately I have a problem with the depdrop.afterChange.

    I have the following Active Form:

    <?php $form = ActiveForm::begin([
    ])
    ?>   
    
    <?php $dataMenu=ArrayHelper::map(\frontend\models\menutype::find()->asArray()->all(), 'menuTypeID', 'MenuTypeDesc'); ?>
    
    <?= $form->field($model, 'masterMenuTypeID')->dropDownList($dataMenu, ['id'=>'MenuType-id', 'prompt'=> 'Select Dish Type...']); ?>
    
    <?= $form->field($model, 'masterMenuTypeDishID')->widget(DepDrop::classname(), [
    'options'=>['id'=>'MenuTypeDish-id'],
    'pluginEvents'=> [
            "depdrop.afterChange"=>"function(event, id, value) { console.log('value: ' + value + ' id: ' + id); }"
    ],
        'pluginOptions'=>[
            'depends'=>['MenuType-id'],
            'placeholder'=>'Choose...',
        'loadingText'=>'Loading...',
            'url'=>Url::to(['/master_menu/dish_type'])        
        ]]); ?>
    
    <?php ActiveForm::end(); ?>
    

    The output of the depdrop.afterChange event give me the value of the previous form field. The out put is: value: 1 id: MenuType-id

    Please note the ID. This is the ID of the first field and not the ID where the event is triggered from.

    Thanks for your help, Yair

    question 
    opened by YairHadari 8
  • Select all button does not initialize controller with multiple select2

    Select all button does not initialize controller with multiple select2

    If to press Select all button the ajax request is not initializing. If I select tags one by one the controller action is working fine. My code _form

    field($user, 'country_region')->widget(Select2::classname(), [
        'data'=> ['ee'=>'Europe', 'pa' => 'Pacific'],
        'options' => [
            'placeholder' => 'Select regions',
            'multiple' => true
        ],
        'pluginOptions'=>[
            'allowClear' => true,
        ]
    ]);
    ?>
    
    field($user, 'country_field')->widget(DepDrop::classname(), [
        'data' => $user->DropCountry,
        'options' => [
            'placeholder' => 'Select countries',
            'multiple' => true
        ],
        'type' => DepDrop::TYPE_SELECT2,
        'select2Options'=>['pluginOptions'=>['allowClear'=>true]],
        'pluginOptions'=>[
            'depends'=>[Html::getInputId($user, 'country_region')],
            'url' => Url::to(['/user/admin/country-region']),
            'loadingText' => 'Loading countries',
        ]
    ]);
    

    Controller

    public function actionCountryRegion() {
            $out = [];
            if (isset($_POST['depdrop_parents'])) {
                $id = end($_POST['depdrop_parents']);
                $list = Countries::find()->andWhere(['region'=>$id])->asArray()->all();
                $selected  = null;
                if ($id != null && count($list) > 0) {
                    $selected = '';
                    foreach ($list as $i => $account) {
                        $out[] = ['id' => $account['country'], 'name' => $account['country_name']];
                        if ($i == 0) {
                            $selected = $account['country'];
                        }
                    }
                    // Shows how you can preselect a value
                    echo Json::encode(['output' => $out, 'selected'=>$selected]);
                    return;
                }
            }
            echo Json::encode(['output' => '', 'selected'=>'']);
        }
    
    wontfix 
    opened by KirillRyzhkov 7
  • Widget populates Select properly but not selected option

    Widget populates Select properly but not selected option

    Hello,

    I have a very simple use case where at the backend I have the following setup;

    public function actionStrength()
    {
        $out = [];
        if (isset($_POST['depdrop_parents'])) {
            $parents = $_POST['depdrop_parents'];
    
            if ($parents != null) {
                $testconfig_id = $parents[0];
                $strength=\common\models\Testconfig::findOne($testconfig_id)->strength;
                    $out = [
                        ['id'=>'1', 'name'=>'Easy'],
                        ['id'=>'2', 'name'=>'Normal'],
                        ['id'=>'3', 'name'=>'Difficult'],
                    ];
                    $selected=strval($strength);
                echo Json::encode(['output'=>$out, 'selected'=>$selected]);
                return;
            }
        }
        echo Json::encode(['output'=>'', 'selected'=>'']);
    }
    

    The logs show the backend is returning the correct json data as follows (notice the selected element is "3") {"output":[ {"id":"1","name":"Easy"}, {"id":"2","name":"Normal"}, {"id":"3","name":"Difficult"} ], "selected":"3" }

    The issue is that the item selected from the backend is not selected by the widget even though it populates properly. Please advise as all the rules have been followed.

    Regards,

    Adam

    enhancement 
    opened by dbd5 7
  • DepDrop in TabularForm with Select2

    DepDrop in TabularForm with Select2

    Prerequisites

    • [x ] I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
    • [ x] The issue still exists against the latest master branch of yii2-widget-depdrop.
    • [x ] This is not an usage question. I confirm having gone through and read the documentation for ActiveForm and ActiveField.
    • [x ] This is not a general programming / coding question. (Those should be directed to the webtips Q & A forum).
    • [ x] I have attempted to find the simplest possible steps to reproduce the issue.
    • [ x] I have included a failing test as a pull request (Optional).

    Hi!

    This extension is really a great help!

    Unfortunately, I try to use DepDrop with TabularForm. As far as I've understood, I do need for every entry a new id to make a unique dependency between parent and child. I try the following solution, but it won't work and ends with the error: Invalid Configuration – yii\base\InvalidConfigException The 'pluginOptions["depends"]' property must be set and must be an array of dependent dropdown element identifiers.

    Is it possible to use an anoy. function and if not, is there any workaround to use it with TabularForms?

    Thank you for help and best regards, Toby

    `'tbl_company_id' => [ 'label' => Yii::t('app', 'Company'), 'type' => TabularForm::INPUT_WIDGET, 'widgetClass' => \kartik\widgets\Select2::className(), 'options' => function($model, $key, $index, $widget) { $initCompany = empty($model['tbl_company_id']) ? '' : \app\models\Company::findOne($model['tbl_company_id'])->name; return [
    'options' => [ 'id' => 'tbl_company_id-id_' . $model['id'], ], 'initValueText' => $initCompany, 'pluginOptions' => [ 'allowClear' => true, 'minimumInputLength' => 3, 'language' => [ 'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"), ], 'ajax' => [ 'url' => \yii\helpers\Url::to(['/company/list']), 'dataType' => 'json', 'data' => new JsExpression('function(params) { return {q:params.term}; }') ], 'escapeMarkup' => new JsExpression('function (markup) { return markup; }'), 'templateResult' => new JsExpression('function(person) { return person.text; }'), 'templateSelection' => new JsExpression('function (person) { return person.text; }'), ], ]; },
    'columnOptions' => ['width' => '200px'] ], 'tbl_person_id' => [ 'label' => Yii::t('app_company', 'Person'), 'type' => TabularForm::INPUT_WIDGET,
    'widgetClass' => DepDrop::className(),

              'options' => [    
                'type' => DepDrop::TYPE_SELECT2,
                  
                'options' => [
                    'placeholder' => 'Select ...',
                ],
                  
                'select2Options' => [
                    'pluginOptions' => [
                        'allowClear' => true,
                        'initValueText' => 'test',
                        ]
                ],
            
                'pluginOptions' => [
                    'depends' => function($model, $key, $index, $widget) { return ['tbl_company_id' . $model['id']]; },                   
                    
                    'initialize' => empty($model['id']) ? false : true,
                    'url' => Url::to(['/person/depdrop']),
                    'loadingText' => 'Loading Persons...',
                ]
            ], 
            
            'columnOptions' => ['width' => '200px'],
        ],`
    

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

    opened by strtob 5
  • Select2 ajax loading

    Select2 ajax loading

    How do you combine a depdrop widget as Select2 that does ajax loading?

    eg If used as select2 field:

    $form->field($model, 'my_field')->widget(Select2::classname(), [
        'data' => [],
        'pluginOptions' => ['ajax' => ['url' => '/path/to/ajax']],
    ]);
    

    But used as DepDrop doesn't have the same result:

    $form->field($model, 'my_field')->widget(DepDrop::classname(), [
        'type' => DepDrop::TYPE_SELECT2,
        'data' => [],
        'pluginOptions' => ['depends' => ['field1'], 'url' => '/path/to/ajax'],
        'select2Options' => [
            'pluginOptions' => ['ajax' => ['url' => '/path/to/ajax']],
        ]
    ]);
    

    Seems url is mandatory in DepDrop and that will populate Select2 field, but Id on't want it to be populated until user enters something in the select2 field, then run an ajax call to match something entered in the field and pass input from the dep field as parameter to this ajax call.

    I can't find any demo on this. What is the correct way to implement this?


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

    wontfix 
    opened by cluwong 5
  • Validation not working on dependent field

    Validation not working on dependent field

    Validation only works for parent dropdown. In the model I have

    ['event_field', 'status_field'], 'required']
    
    field($model, 'event_field')->dropDownList(ArrayHelper::map(OrdersStage::find()->asArray()->all(), 'stage_id', 'stage_name'), ['id'=>'e_id', 'prompt'=>'']); ?>
    field($model, 'status_field')->widget(DepDrop::classname(), [ 'options'=>['id'=>'substatus-id'], 'pluginOptions'=>[ 'depends'=>['e_id'], 'placeholder'=>'', 'url' => Url::to(['/orders/events-group']), 'loadingText' => 'Loading statuses...', 'initialize' => false, ] ]); ?>

    If status_field is empty validation is not triggered.

    wontfix 
    opened by KirillRyzhkov 5
  • Issue: Class 'kartik\form\DepDrop' not found

    Issue: Class 'kartik\form\DepDrop' not found

    I installed yii2-widgets via composer into my application. But when I include it in my _form.php view file, it says:

    Class 'kartik\form\DepDrop' not found

    I also tried including it like: use kartik\widgets\DepDrop;

    but still didn't work for me.

    I then installed the individual package by: php composer.phar require kartik-v/yii2-widget-depdrop "*"

    but it didn't resolve my problem.

    question 
    opened by mhashimmaqbool 5
  • you need to edit 'dependent-dropdown.js' in your assets directory.

    you need to edit 'dependent-dropdown.js' in your assets directory.

    you need to edit 'dependent-dropdown.js' in your assets directory. on line 97, before: on('depdrop:change change select2:select krajeeselect2:cleared' after: on('depdrop:change change select2:select krajeeselect2:cleared krajeeselect2:selectall krajeeselect2:unselectall' this is help me.

    Originally posted by @fateevv85 in https://github.com/kartik-v/yii2-widget-depdrop/issues/28#issuecomment-405094045

    wontfix 
    opened by tarmof 4
  • Dep dropdown list won't display returned result - Uncaught error

    Dep dropdown list won't display returned result - Uncaught error

    I'm getting the following error, after the Json data returned from Controller action:

    Uncaught TypeError: Cannot read property 'toString' of null at a.createOption (dependent-dropdown.min.js:10) at a.renderSelect (dependent-dropdown.min.js:10) at Object.success (dependent-dropdown.min.js:10) at fire (jquery.js:3187) at Object.fireWith [as resolveWith] (jquery.js:3317) at done (jquery.js:8757) at XMLHttpRequest. (jquery.js:9123)

    Using Yii 2.0.12, jQuery v2.2.4 and dependent-dropdown v1.4.7. Have tested on both Chrome and Firefox.

    I haven't used this form for more than a week and the error happened today. Noticed that dependent-dropdown was updated on Jul 25. Not sure if this is related or are there any version clashes?

    opened by cluwong 4
  • DepDrop Multiple=>true with Select2 showing a default value with nothing

    DepDrop Multiple=>true with Select2 showing a default value with nothing

    I'm using Select2 + DepDrop with the multiple option true. I have 2 multiple selects: PARENTS -> CHILD 1

    When I load my CHILD 1 I'm getting a blank option as default selected(image). captura de tela de 2015-03-05 11 13 04

    In my controller I have:

    echo Json::encode(['output' => $out, 'selected'=>'']);
    

    but it is the same result as:

    echo Json::encode(['output' => $out]);
    

    No I don't want a default value to my CHILD 1, how can I remove it?


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

    enhancement 
    opened by franciscocabral 8
Releases(v1.0.6)
  • v1.0.6(Apr 19, 2019)

  • v1.0.5(Oct 9, 2018)

    Version 1.0.5

    Date: 09-Oct-2018

    • Bump composer dependencies.
    • Add Bootstrap 4.x support.
    • Reorganize all source code in src directory.
    • Add github contribution and issue/PR log templates.
    • Update copyright year to current.
    Source code(tar.gz)
    Source code(zip)
  • v1.0.4(Jan 10, 2016)

    Date: 10-Jan-2016

    • Enhancements for PJAX based reinitialization. Complements enhancements in kartik-v/yii2-krajee-base#52 and kartik-v/yii2-krajee-base#53.
    Source code(tar.gz)
    Source code(zip)
  • v1.0.3(Dec 25, 2015)

    Date: 16-Dec-2015

    • (enh #25): Implement new standalone DepDropAction for usage in Controller.
    • (enh #26): Enhance update of Select2 plugin values after dependency change.
    Source code(tar.gz)
    Source code(zip)
  • v1.0.2(Jun 26, 2015)

  • v1.0.1(May 22, 2015)

  • v1.0.0(Nov 9, 2014)

Owner
Kartik Visweswaran
Kartik Visweswaran
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
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
A easy way to install your basic yii projetc, we have encrypt database password in phpfile, my class with alot funtions to help you encrypt and decrypt and our swoole server install just run ./yii swoole/start and be happy!

Yii 2 Basic Project Template with swoole and Modules Yii 2 Basic Project Template is a skeleton Yii 2 application best for rapidly creating small proj

null 3 Apr 11, 2022
PHPR or PHP Array Framework is a framework highly dependent to an array structure.

this is new repository for php-framework Introduction PHPR or PHP Array Framework is a framework highly dependent to an array structure. PHPR Framewor

Agung Zon Blade 2 Feb 12, 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
Yii2 SwitchInput widget turns checkboxes and radio buttons into toggle switchinputes

Yii2 SwitchInput widget turns checkboxes and radio buttons into toggle switchinputes

Kartik Visweswaran 38 Sep 21, 2022
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
An extended bootstrap alert and alert block widget for Yii2 (sub repo split from yii2-widgets)

yii2-widget-alert This extension contains a couple of useful widgets. The Alert widget extends the \yii\bootstrap\Alert widget with more easy styling

Kartik Visweswaran 28 Mar 12, 2022
Yii 2: The Fast, Secure and Professional PHP Framework

Yii 2 is a modern framework designed to be a solid foundation for your PHP application. It is fast, secure and efficient and works right out of the bo

Yii Software 14k Dec 31, 2022
Yii 2 Bootstrap 5 Extension

Twitter Bootstrap 5 Extension for Yii 2 This is the Twitter Bootstrap extension for Yii framework 2.0. It encapsulates Bootstrap 5 components and plug

Yii Software 48 Dec 14, 2022
Yii-specific middleware

Yii Middleware The package ... Requirements PHP 8.0 or higher. Installation The package could be installed with composer: composer require yiisoft/yii

Yii Software 9 Nov 4, 2022
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
Geography module for Yii 2

Geography module for Yii 2

Sergey Fedorov 13 Oct 20, 2018
Code generation with logic-less templates for Yii

Caviar Code generation with logic-less templates for Yii. Caviar vs Gii You might be wondering why you should use Caviar instead of Gii, so let us tak

Christoffer Niska 10 Dec 19, 2015
This extension provides a view renderer for Pug templates for Yii framework 2.0 applications.

This extension provides a view renderer for Pug templates for Yii framework 2.0 applications.

Revin Roman 9 Jun 17, 2022
Extension for creating and sending emails for the Yii PHP framework.

yii-emailer Extension for creating and sending emails for the Yii PHP framework. Usage Migrate the email_message database table by this command: yiic

Digia 12 Mar 30, 2022
This extension provides Flysystem integration for the Yii framework

This extension provides Flysystem integration for the Yii framework. Flysystem is a filesystem abstraction which allows you to easily swap out a local filesystem for a remote one.

Alexander Kochetov 276 Dec 9, 2022
Password strategies for Yii

Password strategies are specifications for how passwords should be encoded and verified and how complicated user supplied passwords should be.

Charles Pick 76 Apr 22, 2022
A framework agnostic, developer friendly wrapper around Fractal

A developer friendly wrapper around Fractal Fractal is an amazing package to transform data before using it in an API. Unfortunately working with Frac

Spatie 356 Dec 29, 2022