Reputation: 139
i am trying to create a dependent dropdown in yii2 basic but it is not working as expected. below is the code to create the dropdown
<?= $form->field($model,'grp_name')->dropDownList(
ArrayHelper::map( Maingroup::find()->all(), 'id', 'name'),
[
'prompt'=>'Select your group',
'onchange'=>' $.post( "index.php?r=memberdetail/lists&id='.'"+$(this).val(), function( data ) {
$( "select#memberdetail-sub_grp" ).html( data );
});'
]); ?>
<?= $form->field($model,'sub_grp')->dropDownList(
ArrayHelper::map(NewGroup::find()->all(), 'id', 'group_num'),
[
'prompt'=>'Select your sub-group',
]); ?>
my lists action in memberdetail controller is
public function actionLists($id)
{
$countsubgroup = NewGroup::find()
->where(['group_name' => $id])
->count();
$subgroup = NewGroup::find()
->where(['group_name' => $id])
->all();
if ($countsubgroup > 0) {
foreach ($subgroup as $name) {
echo "<option value='" . $name->id . "'>" . $name->group_num . "</option>";
}
} else {
echo "<option> - </option>";
}
}
what actually is happening is this problem i think due to which it is not going to the memberdetail controller and not calling to public function actionLists($id)
Upvotes: 1
Views: 1614
Reputation: 713
If you have enabled the pretty url, and not getting the index.php in your site url then you have to change the post action like below.
'onchange'=>' $.post( "lists?id='.'"+$(this).val(), function( data ) {
$( "select#memberdetail-sub_grp" ).html( data );
});'
If not then please mention what exact error you are getting in 400 bad request
Upvotes: 0
Reputation: 4261
Simple way to Create dependent Dropdown
first create DependentController.php
in your controller
folder like
<?php
namespace app\controllers;
use yii\helpers\Html;
use Yii;
class DependentController extends \yii\web\Controller
{
public function actionGetsubgroup($id)
{
$rows = NewGroup::find()->where(['group_name' => $id])
->all();
echo "<option value=''>---Select State---</option>";
if(count($rows)>0){
foreach($rows as $row){
echo "<option value='$row->id'>$row->group_num</option>";
}
}
else{
echo "";
}
}
}
Your _form.php
<?= $form->field($model,'grp_name')->dropDownList(ArrayHelper::map( Maingroup::find()->all(), 'id', 'name'),
[
'prompt'=>'Select your group',
'onchange'=>'$.get( "'.Url::toRoute('dependent/getsubgroup').'", { id: $(this).val() } ).done(function( data ) { $( "#'.Html::getInputId($model,'sub_grp').'" ).html( data ); } );'
]); ?>
<?php if(!empty($model,'sub_grp')) : ?>
<?= $form->field($model,'sub_grp')->dropDownList(ArrayHelper::map(NewGroup::find()->all(), 'id', 'group_num'), ['prompt' => '---Select Sub-Group---']); ?>
<?php else : ?>
<?= $form->field($model,'sub_grp')->dropDownList([], ['prompt' => '---Select Sub-Group---']); ?>
<?php endif; ?>
Upvotes: 1