Di tutorial sebelumnya kita telah berhasil membuat dependent dropdown tanpa menggunakan widget. Tips kali ini tentang dependent dropdown, namun menggunakan widget yaitu Depdrop dari Kartik.
1. Install depdrop widget :
1 |
$ php composer.phar require kartik-v/yii2-widget-depdrop "@dev" |
2. Buat public action baru di frontend/controllers/SiteController.php :
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public function actionDepdrop() { $model = new \backend\models\Departments(); if ($model->load(Yii::$app->request->post())) { $model->department_created_date = date('Y-m-d h:m:s'); $model->save(); return $this->redirect(['view', 'id' => $model->department_id]); } else { return $this->render('depdrop', [ 'model' => $model, ]); } } |
Kemudian di frontend/views/site buat sebuah file depdrop.php.
3. Pada depdrop.php, jangan lupa menyertakan use :
1 2 3 |
use kartik\depdrop\DepDrop; use kartik\select2\Select2; use yii\helpers\Url; |
Buat array Company :
1 |
$company = ArrayHelper::map(Companies::find()->all(),'company_id','company_name'); |
Kemudian buat dropdownlist untuk Company :
1 2 3 4 5 6 7 8 9 |
<?= $form->field($model, 'companies_company_id')->widget(Select2::classname(), [ 'data' => $company, 'options'=>['placeholder'=>Yii::t('app','Select Company')], 'pluginOptions' => [ 'allowClear' => true, ], ]); ?> |
Dan dropdownlist untuk Branch :
1 2 3 4 5 6 7 8 9 10 11 12 |
<?= $form->field($model, 'branches_branch_id')->widget(DepDrop::classname(), [ 'type'=>DepDrop::TYPE_SELECT2, 'options'=>['id'=>'departments-branches_branch_id'], 'select2Options'=>['pluginOptions'=>['allowClear'=>true]], 'pluginOptions'=>[ 'depends'=>['departments-companies_company_id'], 'url'=>Url::to(['/site/branches']), 'placeholder'=>Yii::t('app','Select Branch'), ] ]); ?> |
4. Buat actionBranches di SiteController.php , sertakan
1 |
use yii\helpers\Json; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public function actionBranches() { $out = []; if (isset($_POST['depdrop_parents'])) { $parents = $_POST['depdrop_parents']; if ($parents != null){ $cat_id = $parents[0]; $out = \backend\models\Branches::find() ->where(['companies_company_id'=>$cat_id]) ->select(['branch_id','branch_name AS name'])->asArray()->all(); echo Json::encode(['output'=>$out, 'selected'=>'']); return; } } } |