Dedikisme's Blog

Ngeblog biar dibilang eksis

Depdrop Yii2 Tutorial

Depdrop pada Yii2 adalah sebuah ekstensi untuk kondisional dropdown dengan ajak yang mempengaruhi value dari dropdown lain, contohnya misal untuk kasus pemilihan provinsi yang berdampak pada value pada dropdown kota. Untuk caranya pertama masukkan repositori kartik widget pada require

1
"kartik-v/yii2-widgets": "dev-master",

sehingga composer.json akan berisi seperti dibawah

composer.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
{
  "name": "yiisoft/yii2-app-advanced",
  "description": "Yii 2 Advanced Application Template",
  "keywords": ["yii2", "framework", "advanced", "application template"],
  "homepage": "http://www.yiiframework.com/",
  "type": "project",
  "license": "BSD-3-Clause",
  "support": {
      "issues": "https://github.com/yiisoft/yii2/issues?state=open",
      "forum": "http://www.yiiframework.com/forum/",
      "wiki": "http://www.yiiframework.com/wiki/",
      "irc": "irc://irc.freenode.net/yii",
      "source": "https://github.com/yiisoft/yii2"
  },
  "minimum-stability": "dev",
  "require": {
      "php": ">=5.4.0",
      "yiisoft/yii2": "*",
      "yiisoft/yii2-bootstrap": "*",
      "yiisoft/yii2-swiftmailer": "*",
      "kartik-v/yii2-widgets": "dev-master"
  },
  "require-dev": {
      "yiisoft/yii2-codeception": "*",
      "yiisoft/yii2-debug": "*",
      "yiisoft/yii2-gii": "*"
  },
  "suggest": {
      "codeception/codeception": "Codeception, 1.8.*@dev is currently works well with Yii.",
      "codeception/specify": "BDD style code blocks for PHPUnit and Codeception",
      "codeception/verify": "BDD Assertions for PHPUnit and Codeception",
      "yiisoft/yii2-faker": "Fixtures generator for Yii2 based on Faker lib"
  },
  "scripts": {
      "post-create-project-cmd": [
          "yii\\composer\\Installer::setPermission"
      ]
  },
  "config": {
      "process-timeout": 1800
  },
  "extra": {
      "writable": [
          "backend/runtime",
          "backend/web/assets",

          "frontend/runtime",
          "frontend/web/assets"
      ]
  }
}

kemudian update composer

1
$ composer update

buat 2 table, table city dan table province;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
CREATE TABLE IF NOT EXISTS `city` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) DEFAULT NULL,
  `province_id` int(10) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `province_id` (`province_id`),
  KEY `id` (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=503 ;

CREATE TABLE IF NOT EXISTS `province` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=35 ;

buat model nya dan isi data – data province dan city

buat fungsi di model

Province.php
1
2
3
4
5
6
7
8
<?php
 public static function getOptions(){
        $data=  static::find()->all();
       $value=(count($data)==0)? [''=>'']: \yii\helpers\ArrayHelper::map($data, 'id','name');

        return $value;
    }
?>
City.php
1
2
3
4
5
6
  public static function getOptionsbyProvince($province_id) {
        $data = static::find()->where(['province_id'=>$province_id])->select(['id','name'])->asArray()->all();
        $value = (count($data) == 0) ? ['' => ''] : $data;

        return $value;
    }

kemudian pada form

_form.php
1
2
3
4
5
6
7
8
9
10
11
  <?= $form->field($model, 'province')->dropDownList(Province::getOptions(), ['id' => 'cat-id', 'class'=>'input-large form-control']); ?>
    
    <?= $form->field($model, 'city')->widget(DepDrop::classname(), [
    'options'=>['id'=>'subcat-id', 'class'=>'input-large form-control'],
    'pluginOptions'=>[
        'depends'=>['cat-id'],
        'placeholder'=>'Select...',
        'url'=>Url::to(['/customer/subcat'])
    ]
]);
    ?>

dan tambahkan actionSubcat pada Controller

CustomerController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  <?php
  public function actionSubcat() {
        $out = [];
        if (isset($_POST['depdrop_parents'])) {
            $parents = $_POST['depdrop_parents'];
            if ($parents != null) {
                $cat_id = $parents[0];
                $out = \common\models\City::getOptionsbyProvince($cat_id);
                echo Json::encode(['output' => $out, 'selected' => '']);
                return;
            }
        }
        echo Json::encode(['output' => '', 'selected' => '']);
    }
    ?>

Comments