You are viewing revision #6 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 or see the changes made in this revision.
I have read http://www.yiiframework.com/wiki/24/creating-a-dependent-dropdown/ (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 http://demos.krajee.com/widget-details/depdrop, 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(
[items],
[options]
);
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-',
'onchange'=>'
$.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')
->dropDownList(
$dataPost,
['id'=>'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)
{
$posts = \common\models\Post::find()
->where(['category_id' => $id])
->orderBy('id DESC')
->all();
if (!empty($posts)) {
foreach($posts as $post) {
echo "<option value='".$post->id."'>".$post->title."</option>";
}
} else{
echo "<option>-</option>";
}
}
My adjusts
View
<?php use yii\helpers\ArrayHelper; use app\models\Estado; use yii\helpers\Html; use yii\helpers\Url; $estado = ArrayHelper::map(Estado::find()->all(), 'esta_codigo', 'esta_nome'); echo $form->field($model, 'esta_codigo')->dropDownList( $estado, [ 'prompt'=>'Selecione um estado', 'onchange'=>' $.get( "'.Url::toRoute('/aluno/municipio').'", { id: $(this).val() } ) .done(function( data ) { $( "#'.Html::getInputId($model, 'muni_codigo').'" ).html( data ); } ); ' ] ); echo $form->field($model, 'muni_codigo')->dropDownList(['prompt'=>'Selecione um estado']) ?>
Controller
public function actionMunicipio($id){ $rows = \app\models\Municipio::find()->where(['esta_codigo' => $id])->all(); echo "<option>Selecione um municipio</option>"; if(count($rows)>0){ foreach($rows as $row){ echo "<option value='$row->muni_codigo'>$row->muni_nome</option>"; } } else{ echo "<option>Nenhum municipio cadastrado</option>"; } }
question
For a yii2 beginner can you explain in 2 words what is it with \common\models\Post ? is it in yii2 core? or is a "extra layer" between Active record and the models? I just use it I have a Fatal error: Class 'common\models\Post' not found
Good tutorial, but the $.post part didn't work to me. Here my adjustments
$.post("'.Yii::$app->urlManager->createUrl('posts/lists') . '", {id:$(this).val()}, function( data ) { $( "select#title" ).html( data ); });
My own adjustments
Thank you for the tutorial. But your codes haven't worked for me. So, I changed my codes like that:
In view
<?php echo $form->field(new app\models\Fealsahe(), 'idsahe')->dropDownList( ArrayHelper::map(\app\models\Fealsahe::find()->all(), 'idsahe', 'emelad'), [ 'onchange' => ' $.post( "' . Url::toRoute('getoperations') . '", {id: $(this).val()}, function(res){ $("#emeliyyatlar").html(res); } ); ', ] ); echo $form->field(new \app\models\Emellist(), 'emelad')->dropDownList( [], [ 'prompt' => 'Fəaliyyət sahəsini seçin', 'id' => 'emeliyyatlar' ] ); ?>
In controller
public function actionGetoperations() { if ($id = Yii::$app->request->post('id')) { $operationPosts = \app\models\Emellist::find() ->where(['idsahe' => $id]) ->count(); if ($operationPosts > 0) { $operations = \app\models\Emellist::find() ->where(['idsahe' => $id]) ->all(); foreach ($operations as $operation) echo "<option value='" . $operation->idemel . "'>" . $operation->emelad . "</option>"; } else echo "<option>-</option>"; } }
H2H!
Thanks.
the post request does not work to me. this my modify..
<?php
use yii\helpers\ArrayHelper;
$arrayParams = ['id' => ''];
$params = array_merge(['sells/lists'], $arrayParams);
$dataCategory=ArrayHelper::map(\common\models\Category::find()->asArray()->all(), 'id', 'name');
echo $form->field($model, 'category_id')->dropDownList($dataCategory, ['prompt'=>'-Choose a Category-', 'onchange'=>' $.post( "'.Yii::$app->urlManager->createUrl($params).'"+$(this).val(), function( data ) { $( "select#title" ).html( data ); }); ']); $dataPost=ArrayHelper::map(\common\models\Post::find()->asArray()->all(), 'id', 'title'); echo $form->field($model, 'title') ->dropDownList( $dataPost, ['id'=>'title'] );
?>
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.