我有一个客户字段,它依赖于一个项目字段。
在我的表单中,我有一个项目的下拉列表,我需要我的第二个客户下拉列表根据项目动态变化。
我在web上的一些地方找到了解决方案,但阵列并没有改变。
有人能帮上忙吗?
我的表单:
$dataProject=ArrayHelper::map(Project::find()->asArray()->all(), 'id', 'name');
echo $form->field($model, 'project_id')->dropDownList($dataProject,
['prompt'=>'-Choose a Project-',
'onchange'=>'
$.post( "'.Yii::$app->urlManager->createUrl('customer/lists?id=').'"+$(this).val(), function( data ) {
$( "select#title" ).html( data );
});
']);
$dataPost=ArrayHelper::map(Customer::find()->asArray()->all(), 'id', 'first_name');
echo $form->field($model, 'customer_id')
->dropDownList(
$dataPost,
['id'=>'title']
);
客户控制器中的代码:
public function actionLists($id) {
$countPosts = Customer::find()
->where(['project_id' => $id])
->count();
$posts = Customer::find()
->where(['project_id' => $id])
->orderBy('id DESC')
->all();
if($countPosts>0) {
foreach($posts as $post){
echo "<option value='".$post->id."'>".$post->first_name."</option>";
}
}
else{
echo "<option>-</option>";
}
}
发布于 2018-05-29 03:49:17
到目前为止,当您可以访问jquery时,将下拉选项添加到select中的最佳方法是使用.each()
,但是您需要从controller/action
中以json
形式提供选项,而不是创建html,然后将html添加到下拉列表中。
然后使用$.post
并为id
添加带有url
的查询字符串,而您可以使用data
选项发送id
。
将您的onchange
函数更改为以下内容
'onchange'=>'
$.post( "'.Yii::$app->urlManager->createUrl('/customer/lists').'", {id:$(this).val()},function( data ) {
//this will clear the dropdown of the previous options
$("#title").children("option").remove();
//optionally you can use the following if you have a placeholder in the dropdown so that the first option is not removed
//$("#title").children("option:not(:first)").remove();
$.each(data, function(key, value) {
$("#title")
.append($("<option></option>")
.attr("value",key)
.text(value));
});
});
然后,您将对Customer
表查询两次,一次是对所有记录进行计数,一次是对所有客户列表进行查询
$countPosts = Customer::find()
->where(['project_id' => $id])
->count();
$posts = Customer::find()
->where(['project_id' => $id])
->orderBy('id DESC')
->all();
您可以简单地查询客户,并在结果集$posts
上使用php:count()
函数来计算记录总数。
$posts = Customer::find()
->where(['project_id' => $id])
->orderBy('id DESC')
->all();
$countPosts = count($post);
但我们无论如何都不需要count
这只是为了提供信息,将您的操作actionLists()
更改为下面并删除参数$id
,因为我们正在发送带有post
的id。
public function actionLists() {
//set the response format to JSON
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
//get the id
$id = Yii::$app->request->post ( 'id' );
$posts = Customer::find ()
->where ( [ 'project_id' => $id ] )
->orderBy ( 'id DESC' )
->all ();
return ArrayHelper::map ( $posts , 'id' , 'first_name' );
}
除了以上所有的工作之外,你应该习惯于以扩展或插件的形式使用可用的资源,其中一个是,它做同样的事情,而编写javascript和从服务器端提供数据的痛苦更少。
https://stackoverflow.com/questions/50568761
复制相似问题