原理:
通过下拉列表onchange事件,向服务器获取另一个下拉列表的内容(在控制器中填充actionMyproduct内容)。代码中黑色加粗的地方是空易错的地方。
视图文件
<?php
use yii\widgets\ActiveForm;
use common\helpers\Url;
use yii\helpers\Html;
use common\enums\WorkOrderStatusEnum;
use common\helpers\ArrayHelper;
$form = ActiveForm::begin([
'id' => $model->formName(),
'enableAjaxValidation' => true,
'validationUrl' => Url::to(['ajax-edit', 'id' => $model['id']),
]);
?>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title">新工单</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-sm-4">
<?= $form->field($model, 'member_id')->dropDownList(ArrayHelper::map($customer,'id', 'realname'),
['prompt'=>'-选择客户-',
'onchange'=>'
$.get( "'.Url::toRoute('/member/order/myproduct').'", { id: $(this).val() } )
.done(function( data ) {
$( "#'.Html::getInputId($model, 'product_id').'" ).html( data );
});
']);
?>
<?= $form->field($model, 'product_id')->dropDownList(ArrayHelper::map($myproduct,'id', 'categary_name'),
['prompt'=>'-选择已购产品-']) ?>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
<button class="btn btn-primary" type="submit">保存</button>
</div>
<?php ActiveForm::end(); ?>
视图说明:$customer,$myproduct,是控制器给的变量。
控制器
// 已购产品列表
public function actionMyproduct($id)
{
$myproducts = Myproduct::find()
->where(['member_id' => $id])
->asArray()
->all();
if(!$myproducts){
echo "<option value='" . 0 . "'>" . "</option>";
}
foreach ($myproducts as $myproduct) {
echo "<option value='" . $myproduct['id'] . "'>" . $myproduct['categary_name'] . "</option>";
}
}
完成效果
[网上大多是某个人的内容,缺少代码,转载且不完整。如果可用,请点个zan]
网友评论