Creating a Dependent Dropdown From Scratch

You are viewing revision #4 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#5) »

I have read (Dependen Dropdown Yii1), but I cant implementation in Yii2 because Yii2 not built-in AJAX functionality hem.. I am search about it and get this statement

qiangxue commented on Aug 28, 2013 In 2.0 we removed most in-page js code. You should write explicit js code in external js files to achieve similar result as in 1.1. The code is very trivial though.

So we must create own code hehe oh no we can use great extension, this right but some one dislike use third party too much.. Oke I try to explain You about this classic case :)

Create Dropdown

First, You should know how to make dropdown in Yii2, I use activefield

echo $form->field($model, 'name_field')->dropDownList(
The Table

In this case, I have 2 table table category

  • id int primary key auto increment
  • name varchar(255)

table category

  • id int primary key auto increment
  • title varchar(255)
  • content text
  • category_id int
The View
use yii\helpers\ArrayHelper;
$dataCategory=ArrayHelper::map(\common\models\Category::find()->asArray()->all(), 'id', 'name');
	echo $form->field($model, 'category_id')->dropDownList($dataCategory, 
	         ['prompt'=>'-Choose a Category-',
				$.post( "'.Yii::$app->urlManager->createUrl('post/lists?id=').'"+$(this).val(), function( data ) {
				  $( "select#title" ).html( data );
	$dataPost=ArrayHelper::map(\common\models\Post::find()->asArray()->all(), 'id', 'title');
	echo $form->field($model, 'title')

Yii2 have change chtml list be ArrayHelper::map.. so You should use library Array helper

use yii\helpers\ArrayHelper;

The Controller
public function actionLists($id)
		$countPosts = \common\models\Post::find()
				->where(['category_id' => $id])
        $posts = \common\models\Post::find()
				->where(['category_id' => $id])
				->orderBy('id DESC')
			foreach($posts as $post){
				echo "<option value='".$post->id."'>".$post->title."</option>";
			echo "<option>-</option>";

membuat dependent dropdown tanpa extension tambahan

4 1
Viewed: 121 927 times
Version: Unknown (update)
Category: How-tos
Written by: ThePr0f3550r
Last updated by: alrazi
Created on: Jul 2, 2014
Last updated: 3 years ago
Update Article


View all history

Related Articles