Krajee
Thankful to Krajee! BUY A COFFEEor to get more out of us.

The DepDrop widget is a Yii 2 wrapper for the dependent-dropdown jQuery plugin by Krajee. The extension also offers an action class DepDropAction that can be used to generate the dependent option values via ajax response.

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.

Important

This widget can be also installed in isolation outside this bundle if needed. In addition to using via \kartik\widgets namespace, this widget can be also installed from the yii2-widget-depdrop repository and can also be accessed via \kartik\depdrop\Depdrop namespace.

The widget also offers an alternative method of rendering the dropdowns using \kartik\select2\Select2 widget.

Tip

Not seeing the updated content on this page! Hard refresh your browser to clean cache for this page (e.g. SHIFT-F5 on Windows Chrome)

DepDrop supports configuration of the bootstrap library version so that you can use this either with any Bootstrap version 3.x and above. For setting up the bootstrap version for your extension, you can configure the DepDrop::bsVersion property to one of the following.

  • To use with bootstrap 3 library - you can set DepDrop::bsVersion property to any string starting with 3 (e.g. 3 or 3.3.7 or 3.x)

  • To use with bootstrap 4 library - you can set DepDrop::bsVersion property to any string starting with 4 (e.g. 4 or 4.6.0 or 4.x)

  • To use with bootstrap 5 library - you can set DepDrop::bsVersion property to any string starting with 5 (e.g. 5 or 5.1.0 or 5.x)

The following sections describe the pre-requisites for enabling Bootstrap library specific version support in your application and other related controls/overrides.

Global Bootstrap Version


Generally, you may also want to set a default version globally for all Krajee Extensions (instead of setting it for each widget or extension separately). In order to do this, you can setup the bsVersion property within Yii 2 application params (i.e. Yii::$app->params['bsVersion']). To set this up, add this section of code to your application params configuration file (e.g. config/params.php):

'params' => [
    'bsVersion' => '5.x', // this will set globally `bsVersion` to Bootstrap 5.x for all Krajee Extensions
    // other settings
    // 'adminEmail' => 'admin@example.com'
]

If DepDrop::bsVersion property is set, in addition to Yii::$app->params['bsVersion'], the extension level setting (DepDrop::bsVersion property) will override the Yii::$app->params['bsVersion']. If DepDrop::bsVersion property is not set, and Yii::$app->params['bsVersion'] is also not set, DepDrop::bsVersion property will default to 3.x (i.e. Bootstrap 3.x version will be assumed as default).

Yii2 Bootstrap Dependency


You need to install one of yiisoft/yii2-bootstrap or yiisoft/yii2-bootstrap4 or yiisoft/yii2-bootstrap5 extensions manually in your application to enable Bootstrap 3.x or 4.x or 5.x functionality respectively. This dependency has not been pre-built into the composer configuration for Krajee extensions, to allow better control to the developers in configuring their bootstrap library version. If bsVersion is set to 5.x and yiisoft/yii2-bootstrap5 is not installed, then an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap5 extension. If bsVersion is set to 4.x and yiisoft/yii2-bootstrap4 is not installed, then an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap4 extension. Similarly, if bsVersion is set to 3.x and yiisoft/yii2-bootstrap is not installed, an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap extension.

To install yiisoft/yii2-bootstrap5, add the repo to the require section of your application's composer.json.

"yiisoft/yii2-bootstrap5": "@dev"

To install yiisoft/yii2-bootstrap4, add the repo to the require section of your application's composer.json.

"yiisoft/yii2-bootstrap4": "@dev"

To install yiisoft/yii2-bootstrap, add the repo to the require section of your application's composer.json.

"yiisoft/yii2-bootstrap": "@dev"

Override Bootstrap CSS/JS


The Krajee extension asset bundle(s) by default depend on one of the following asset bundles to load the Bootstrap CSS and JS:

  • yii\bootstrap\BootstrapAsset and/or yii\bootstrap\BootstrapPluginAsset for bootstrap 3.x (bsVersion = 3 setting)

  • yii\bootstrap4\BootstrapAsset and/or yii\bootstrap4\BootstrapPluginAsset for bootstrap 4.x ( bsVersion = 4 setting)

  • yii\bootstrap5\BootstrapAsset and/or yii\bootstrap5\BootstrapPluginAsset for bootstrap 5.x (bsVersion = 5 setting)

This is controlled by the property bsDependencyEnabled within the asset bundle (which defaults to true). One can override this and prevent the default yii2 bootstrap assets (CSS & JS) from loading by doing one or all of the following:

  • Global Override: Set Yii::$app->params['bsDependencyEnabled'] to false in your Yii 2 application config params.php. This setting will be applied for all Krajee Extension Asset Bundles that depend on Bootstrap assets.

    'params' => [
        'bsDependencyEnabled' => false, // this will not load Bootstrap CSS and JS for all Krajee extensions
        // you need to ensure you load the Bootstrap CSS/JS manually in your view layout before Krajee CSS/JS assets
        //
        // other params settings below
        // 'bsVersion' => '5.x',
        // 'adminEmail' => 'admin@example.com'
    ]
    
  • Asset Bundle Specific Override: Set bsDependencyEnabled to false for the specific asset bundle within Yii2 Asset Manager component in your Yii 2 application config file.

    // ...
    'components' => [
        'assetManager' => [
            'bundles' => [
                'kartik\form\ActiveFormAsset' => [
                    'bsDependencyEnabled' => false // do not load bootstrap assets for a specific asset bundle
                ],
            ],
        ],
    ],
    

Note

When setting bsDependencyEnabled to false, you need to ensure that your app code/view layout loads the Bootstrap CSS and JS on your view before the Krajee CSS/JS are loaded to ensure that the Krajee extension JS plugins and CSS styles do not get broken.

Icons for Bootstrap


Bootstrap 5.x / 4.x does not include glyphicons or any other icons framework bundled with the library. Krajee extensions therefore will use Font Awesome 5.x icons instead of glyphicons when working with Bootstrap 5.x / 4.x. You can download Font Awesome 5.x icons from the icons website. Alternatively, you can load the free version of Font Awesome from their CDN.

For Krajee extensions and demos, the Font Awesome Free version is used and loaded as the Icons Display Package on all the Yii2 demo layouts. To include font awesome assets on your page, include the following markup on the HEAD section of your view layout file, when bsVersion is set to 4.x or 5.x.

  • Option 1: Font CSS version of Font Awesome:

    <!-- on your view layout file HEAD section -->
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css">
    
  • Option 2: SVG / JS version of Font Awesome (recommended for cleaner scaling vector icons and features like icon layers):

    <!-- on your view layout file HEAD section -->
    <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js" crossorigin="anonymous"></script>
    

    Alternatively, you can use the FontAwesomeAsset from the kartik-v/yii2-icons package to load the SVG/JS version.

    // on your view layout file
    use kartik\icons\FontAwesomeAsset;
    FontAwesomeAsset::register($this);
    

The yii2-widget-depdrop extension can be installed automatically or manually using one of these options:

Composer Package Manager Recommended


Installation via Composer is the recommended and most easy option to install Krajee Yii2 extensions. You can install yii2-widget-depdrop via composer package manager. Either run:

$ php composer.phar require kartik-v/yii2-widget-depdrop "dev-master"

or add:

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

to your application's composer.json file.

Manual Install


You may also manually install the extension to your project (in case your composer install does not work). Just download the source ZIP or TAR ball and extract the extension asset files and folders into your project. You may need to install dependencies manually and also set the namespaces to the extensions in your Yii2 extensions configurations manually.

This widget uses the dependent-dropdown JQuery plugin by Krajee. Refer the plugin documentation for understanding the usage of the dependent dropdown plugin. The widget supports all parameters that one would pass for any Yii Input Widget. The additional parameter settings specially available for the DepDrop widget configuration are:
  • bsVersion: string | int, the bootstrap library version to be used for the extension. Refer the Bootstrap Info section for details and pre-requisites on setting this property.

    • To use with Bootstrap library - you can set this to any string starting with 3 (e.g. 3 or 3.3.7 or 4.x / 3.x)

    • To use with bootstrap 4 - you can set this to any string starting with 4 (e.g. 4 or 4.6.0 or 4.x)

    • To use with bootstrap 5 - you can set this to any string starting with 4 (e.g. 5 or 5.1.0 or 5.x)

  • bsColCssPrefixes: array, the bootstrap grid column css prefixes mapping, the key is the bootstrap versions, and the value is an array containing the sizes and their corresponding grid column css prefixes. The class using this trait, must implement kartik\base\BootstrapInterface. If not set will default to:.

    [
       3 => [
          self::SIZE_X_SMALL => 'col-xs-',
          self::SIZE_SMALL => 'col-sm-',
          self::SIZE_MEDIUM => 'col-md-',
          self::SIZE_LARGE => 'col-lg-',
          self::SIZE_X_LARGE => 'col-lg-',
          self::SIZE_XX_LARGE => 'col-lg-',
       ],
       4 => [
          self::SIZE_X_SMALL => 'col-',
          self::SIZE_SMALL => 'col-sm-',
          self::SIZE_MEDIUM => 'col-md-',
          self::SIZE_LARGE => 'col-lg-',
          self::SIZE_X_LARGE => 'col-xl-',
          self::SIZE_XX_LARGE => 'col-xl-',
       ],
       5 => [
          self::SIZE_X_SMALL => 'col-',
          self::SIZE_SMALL => 'col-sm-',
          self::SIZE_MEDIUM => 'col-md-',
          self::SIZE_LARGE => 'col-lg-',
          self::SIZE_X_LARGE => 'col-xl-',
          self::SIZE_XX_LARGE => 'col-xxl-',
       ],
    ];
    
  • type: int the type of dropdown list to be generated. Should be one of the following values:

    • 1 or DepDrop::TYPE_DEFAULT: render a default HTML select using \yii\helpers\Html::dropDownList.

    • 2 or DepDrop::TYPE_SELECT2: render advanced Select2 using \kartik\select2\Select2 widget.

    If not set the type will default to 1 or DepDrop::TYPE_DEFAULT.

  • data: array the list of option data just like a standard Yii dropDownList, which can be generated using \yii\helpers\ArrayHelper::map(). However, a simple and efficient way to display a record for update, is that you set this to the last selected value and name as a single row array. This is because, the dropdown by default is disabled for select and this list will be overwritten by ajax operation based on dependent parent value. For example, if the last saved record for the dropdown field was id = 4, desc = 'Product 4', you can set the initial data for this field as:

    'data'=>[4=>'Product 4']
    
  • select2Options: array the additional widget configuration options for the Select2. This is applicable only if type is set to DepDrop::TYPE_SELECT2.

  • options: array the HTML attributes for the select element/ dropdown list.

  • pluginOptions: array the options for the depdrop.js plugin. The following options can be configured:

    • url: string The url string for the controller action that will return the Json encoded dependent dropdown data via ajax.

    • depends: array The list of dependent parent dropdown element IDs (HTML ID attributes without any leading #).

    • loading: boolean whether to show a loading progress spin indicator in the dependent select when server is processing the ajax response. Defaults to true.

    • placeholder: string whether the dependent select has a default placeholder (with an empty value), when no records are found. You can set this to a label which will be displayed as an empty value. For optgroups this will be a disabled option. If you set this to null or empty string , it will not be displayed. Defaults to Select ....

    • placeholder: string the message to display when the ajax response returned from the server is null or an empty array. Defaults to No data found.

  • pluginEvents: array the DepDrop JQuery events. You must define events in event-name=>event-function format. All events will be stacked in the sequence. Refer the plugin events documentation for details. For example:

    pluginEvents = [
        "depdrop:init"=>"function() { log('depdrop:init'); }",
        "depdrop:ready"=>"function() { log('depdrop:ready'); }",
        "depdrop:change"=>"function(event, id, value, count) { log(id); log(value); log(count); }",
        "depdrop:beforeChange"=>"function(event, id, value) { log('depdrop:beforeChange'); }",
        "depdrop:afterChange"=>"function(event, id, value) { log('depdrop:afterChange'); }",
        "depdrop:error"=>"function(event, id, value) { log('depdrop:error'); }",
    ];
    

Important

The plugin triggers an ajax call to the server to fetch the dependent dropdown list. You must return the data in a specified Json encoded format. Refer the usage examples in this page for understanding the format in which the server should return data to the ajax response.

Scenario 1

A 3-level nested dependency example.

/*
 * SCENARIO 1: A 3-level nested dependency example
 */
// THE VIEW
use kartik\depdrop\DepDrop;

$catList = [
    1 => 'Electronics',
    2 => 'Books',
    3 => 'Home & Kitchen'
];

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

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

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

// THE CONTROLLER
public function actionSubcat() {
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $out = [];
    if (isset($_POST['depdrop_parents'])) {
        $parents = $_POST['depdrop_parents'];
        if ($parents != null) {
            $cat_id = $parents[0];
            $out = self::getSubCatList($cat_id); 
            // the getSubCatList function will query the database based on the
            // cat_id and return an array like below:
            // [
            //    ['id'=>'<sub-cat-id-1>', 'name'=>'<sub-cat-name1>'],
            //    ['id'=>'<sub-cat_id_2>', 'name'=>'<sub-cat-name2>']
            // ]
            return ['output'=>$out, 'selected'=>''];
        }
    }
    return ['output'=>'', 'selected'=>''];
}

public function actionProd() {
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $out = [];
    if (isset($_POST['depdrop_parents'])) {
        $ids = $_POST['depdrop_parents'];
        $cat_id = empty($ids[0]) ? null : $ids[0];
        $subcat_id = empty($ids[1]) ? null : $ids[1];
        if ($cat_id != null) {
           $data = self::getProdList($cat_id, $subcat_id);
            /**
             * the getProdList function will query the database based on the
             * cat_id and sub_cat_id and return an array like below:
             *  [
             *      'out'=>[
             *          ['id'=>'<prod-id-1>', 'name'=>'<prod-name1>'],
             *          ['id'=>'<prod_id_2>', 'name'=>'<prod-name2>']
             *       ],
             *       'selected'=>'<prod-id-1>'
             *  ]
             */
           
           return ['output'=>$data['out'], 'selected'=>$data['selected']];
        }
    }
    return ['output'=>'', 'selected'=>''];
}

Important

When you set the placeholder property, it creates an option with empty value, which is displayed as the first option in the list. For a dropdown with optgroups as seen in this example, the placeholder prompt will be disabled.

Scenario 2

A 2-level dependency with optgroups generated in dependent dropdown list. In addition, it includes preselected data which you may have in a record update scenario (initial category is set to 'Category 1' and subcategory is set to 'Tablets'). Note: the data property must be set for displaying the preselected value on initialization and must contain the key for the initial value. The subcategory is rendered using the \kartik\select2\Select2 widget.

This example also considers an option where you pass additional params to the ajax call by setting other form input identifiers.

 

Scenario 3

Four level dropdown dependency using \kartik\select2\Select2 widget. Custom loading progress text is set for each dependent dropdown. In addition, it includes preselected values for dropdowns. NOTE: For a nested list scenario where the last child has the initialize plugin property set to true and depends on all 3 dropdowns before. This ensures each dependent list is loaded on initial page load in the right sequence and with the right preset values.

Also you can see in this example, how after every change of a parent value, a preselected default value is possible to be set for each child.

/*
 * SCENARIO 2: A 2-level dependency with optgroups with subcategory to be 
 * rendered by `\kartik\select2\Select2` widget.
 * In addition, it includes preselected data which you may have in a record 
 * update scenario (initial category is set to 'Category 1' and 
 * subcategory is set to 'Tablets'). Note: the `data` property must 
 * must be set for displaying the preselected value on initialization 
 * and must contain the key for the initial value.
 *
 * This example also considers an option where you pass additional `params`
 * to the ajax call by setting other form input identifiers.
 */
// THE VIEW
use kartik\depdrop\DepDrop;

// Parent 
echo $form->field($model, 'cat1')->dropDownList($majorCatList, ['id' => 'cat-id']);

// Additional input fields passed as params to the child dropdown's pluginOptions
echo Html::hiddenInput('input-type-1', 'Additional value 1', ['id' => 'input-type-1']);
echo Html::hiddenInput('input-type-2', 'Additional value 2', ['id' => 'input-type-2']);

// Child # 1
echo $form->field($model, 'subcat1')->widget(DepDrop::classname(), [
    'type' => DepDrop::TYPE_SELECT2,
    'data' => [2 => 'Tablets'],
    'options' => ['id' => 'subcat1-id', 'placeholder' => 'Select ...'],
    'select2Options' => ['pluginOptions' => ['allowClear' => true]],
    'pluginOptions' => [
        'depends' => ['cat1-id'],
        'url' => Url::to(['/site/subcat1']),
        'params' => ['input-type-1', 'input-type-2']
    ]
]);

// THE CONTROLLER
public function actionSubcat1() {
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $out = [];
    if (isset($_POST['depdrop_parents'])) {
        $parents = $_POST['depdrop_parents'];
        if ($parents != null) {
            $cat_id = $parents[0];
            $param1 = null;
            $param2 = null;
            if (!empty($_POST['depdrop_params'])) {
                $params = $_POST['depdrop_params'];
                $param1 = $params[0]; // get the value of input-type-1
                $param2 = $params[1]; // get the value of input-type-2
            }

            $out = self::getSubCatList1($cat_id, $param1, $param2); 
            // the getSubCatList1 function will query the database based on the
            // cat_id, param1, param2 and return an array like below:
            // [
            //    'group1' => [
            //        ['id' => '<sub-cat-id-1>', 'name' => '<sub-cat-name1>'],
            //        ['id' => '<sub-cat_id_2>', 'name' => '<sub-cat-name2>']
            //    ],
            //    'group2' => [
            //        ['id' => '<sub-cat-id-3>', 'name' => '<sub-cat-name3>'], 
            //        ['id' => '<sub-cat-id-4>', 'name' => '<sub-cat-name4>']
            //    ]            
            // ]
            
            
            $selected = self::getDefaultSubCat($cat_id);
            // the getDefaultSubCat function will query the database
            // and return the default sub cat for the cat_id
            
            return ['output' => $out, 'selected' => $selected];
        }
    }
    return ['output' => '', 'selected' => ''];
}

/*
 * SCENARIO 3: Four level dropdown dependency using `\kartik\select2\Select2` widget. Custom loading progress 
 * text is set for each dependent dropdown. In addition, it includes preselected values for dropdowns. 
 * 
 * NOTE: For a nested list scenario where the last child has the `initialize` plugin property set to 
 * `true` and depends on all 3 dropdowns before. This ensures each dependent list is loaded on initial page 
 * load in the right sequence and with the right preset values. Also you can see in this example, how after 
 * every change of a parent value, a preselected default value is possible to be set for each child.
 */
// THE VIEW
use kartik\depdrop\DepDrop;

// Top most parent
echo $form->field($account, 'lev0')->widget(Select2::classname(), [
    'data' => ArrayHelper::map(Account::find()->where('parent IS NULL')->asArray()->all(), 'id', 'name')
]);

// Child level 1
echo $form->field($account, 'lev1')->widget(DepDrop::classname(), [
    'data' => [6 => 'Bank'],
    'options' => ['placeholder' => 'Select ...'],
    'type' => DepDrop::TYPE_SELECT2,
    'select2Options' => ['pluginOptions' => ['allowClear' => true]],
    'pluginOptions' => [
        'depends' => ['account-lev0'],
        'url' => Url::to(['/account/child-account']),
        'loadingText' => 'Loading child level 1 ...',
    ]
]);

// Child level 2
echo $form->field($account, 'lev2')->widget(DepDrop::classname(), [
    'data' => [9 => 'Savings'],
    'options' => ['placeholder' => 'Select ...'],
    'type' => DepDrop::TYPE_SELECT2,
    'select2Options' => ['pluginOptions' => ['allowClear' => true]],
    'pluginOptions' => [
        'depends' => ['account-lev1'],
        'url' => Url::to(['/account/child-account']),
        'loadingText' => 'Loading child level 2 ...',
    ]
]);

// Child level 3
echo $form->field($account, 'lev3')->widget(DepDrop::classname(), [
    'data' => [12 => 'Savings A/C 2'],
    'options' => ['placeholder' => 'Select ...'],
    'type' => DepDrop::TYPE_SELECT2,
    'select2Options' => ['pluginOptions' => ['allowClear' => true]],
    'pluginOptions' => [
        'depends' => ['account-lev2'],
        'initialize' => true,
        'initDepends' => ['account-lev0'],
        'url' => Url::to(['/account/child-account']),
        'loadingText' => 'Loading child level 3 ...'
    ]
]);


// CONTROLLER
public function actionChildAccount() {
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $out = [];
    if (isset($_POST['depdrop_parents'])) {
        $id = end($_POST['depdrop_parents']);
        $list = Account::find()->andWhere(['parent' => $id])->asArray()->all();
        $selected  = null;
        if ($id != null && count($list) > 0) {
            $selected = '';
            foreach ($list as $i => $account) {
                $out[] = ['id' => $account['id'], 'name' => $account['name']];
                if ($i == 0) {
                    $selected = $account['id'];
                }
            }
            // Shows how you can preselect a value
            return ['output' => $out, 'selected' => $selected];
        }
    }
    return ['output' => '', 'selected' => ''];
}

The extension offers an easy method to generate dependent dropdown server actions as an alternative to server code in the examples before. The Dependent Dropdown action kartik\depdrop\DepDropAction can be used to generate the dependent option values via ajax response. A typical usage of this action in your controller could look like below (the example shows a subcategory action id to generate child dropdown values):

// inside the controller
public function actions()
{
    return \yii\helpers\ArrayHelper::merge(parent::actions(), [
        'subcategory' => [
            'class' => \kartik\depdrop\DepDropAction::className(),
            'outputCallback' => function ($selectedId, $params) {
                return [
                    [
                        'id' => 1,
                        'name' => 'Car',
                    ],
                    [
                        'id' => 2,
                        'name' => 'bike',
                    ],
                ];

                // if using with optgroup return something like below instead of above
                return [
                    'group1' => [
                        ['id' => '', 'name' => ''],
                        ['id' => '', 'name' => '']
                    ],
                    'group2' => [
                        ['id' => '', 'name' => ''],
                        ['id' => '', 'name' => '']
                    ]
                ];
            }
        ]
    ]);
}

Note

You can now visit the Krajee Webtips Q & A forum for searching OR asking questions OR helping programmers with answers on these extensions and plugins. For asking a question click here. Select the appropriate question category (i.e. Krajee Plugins) and choose this current page plugin in the question related to field.

The comments and discussion section below are intended for generic discussions or feedback for this plugin. Developers may not be able to search or lookup here specific questions or tips on usage for this plugin.

 
visitors to Krajee Yii2 Demos since 22-May-2017