我想在yii2-advanced app中使用依赖下拉列表,使用2个模型 - BusinessMainCategories(bmc_id, bmc_name) & BusinessSubCategories(bsc_id, bsc_name, bmc_id)
。我将使用位于前端的页面上的下拉列表。我尝试过以下操作,但每次都会显示db中的所有子类别。
我的观看代码是 -
<?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data']]); ?>
<?php
$dataBMC = ArrayHelper::map(\backend\models\BusinessMainCategories::find()->asArray()->all(), 'bmc_id', 'bmc_name');
echo $form->field($model, 'bmc_id')->dropDownList($dataBMC,
['prompt'=>'Choose a Main Category',
'style'=>'width:75%',
'onchange'=>'
$.post("index.php?r=business-sub-categories/lists&id='.'"+$(this).val(),
function(data) {
$("select#business_sub_categories-bsc_id" ).html( data );
});
']);
echo "<br>";
$dataBSC = ArrayHelper::map(\backend\models\BusinessSubCategories::find()->asArray()->all(), 'bsc_id', 'bsc_name');
echo $form->field($model, 'bmc_id')
->dropDownList(
$dataBSC,
['prompt'=>'Choose a Sub Category',
'style'=>'width:75%',
'id'=>'bmc_id']
);
?>
<div class="form-group"><br>
<input type="submit" value="Submit" class='btn btn-success'>
</div>
<?php ActiveForm::end(); ?>
我很困惑,我应该在哪里编写列表函数的代码?我在后端\ controllers \ BusinessSubCategoriesController中写它如下 -
public function actionLists($id)
{
$countBSCategories = BusinessSubCategories::find()->where(['bmc_id' => $id])->count();
$businessSubCategories = BusinessSubCategories::find()->where(['bmc_id' => $id])->all();
if ($countBSCategories > 0) {
foreach ($businessSubCategories as $businessSubCategory) {
echo "<option value='" . $businessSubCategory->bsc_id . "'>" . $businessSubCategory->bsc_name . "</option>";
}
} else {
echo "<option> - </option>";
}
}
我认为该功能没有正确地获得'bmc_id'。请告诉我一个解决方案,通过纠正我的错误使其依赖...
我建议使用get
方法,你在Dropdown中使用相同的字段。所以,改变它。
echo $form->field($model, 'bmc_id')->dropDownList($dataBMC,
['prompt'=>'Choose a Main Category',
'style'=>'width:75%',
'onchange'=>'
$.get( "'.Url::toRoute('business-sub-categories/lists').'", { id: $(this).val() })
.done(function( data ) { $( "#'.Html::getInputId($model, 'attribute').'" ).html( data ); } );'
]);
相同的情景 -
<?= $form->field($model, 'category_id')->dropDownList(ArrayHelper::map(ItemCategory::find()->all(),'id','ic_code'),
['prompt'=>'Select Category',
'onchange' => '
$.post("index.php?r=receiving-order-details/lists&id=' . '"+$(this).val(),function(data){
$("select#receivingorderdetails-sub_category_id").html(data);
});']) ?>
<?= $form->field($model, 'sub_category_id')->dropDownList(ArrayHelper::map(ItemSubCategory::find()->all(),'id','isc_code'),['prompt'=>'Select Sub Category']) ?>