Hi我试图在动态选择中实现一个默认占位符,该占位符链接到另一个选择。我使用存储库来查询数据库,以检索加载到第一个select中的users
clients
。第二个选择是一个链式选择,它有一个占位符,很容易实现。无论如何,我已经尝试了以下操作,但它在select选项的value属性中加载了不正确的ID。
我正在获取身份验证用户客户端,然后客户端在我的存储库中进行项目:
public function getClients()
{
return 'Auth::user()->clients()->orderBy('client_name', 'asc')->lists('client_name','id');;
}
public function getClientsProjects($clientId)
{
$client = Client::find($clientId);
if ( ! $client = Client::find($clientId)) { echo 'client not found'; }
//$projects = $projects = 'Auth::user()->projects()->where('client_id', $client->id)->orderBy('project_name')->get(array('id','project_name'));
$projects = $projects = Project::where('client_id', $client->id)
->orderBy('project_name')
->get(array('id','project_name'));
$response = array();
foreach($projects as $project){
$response[$project->id] = $project->project_name;
}
return $response;
}
在我的任务控制器中,我这样输入:
public function clientsProjects()
{
$clientId = Input::get('option');
return Response::json($this->project->getClientsProjects($clientId));
}
public function create()
{
$tasks = Auth::user()->tasks;
$client_options = $this->project->getClients();
$client_options = array_merge([0 => 'Select a client from the list'], $client_options);
$status = $this->project->getStatus();
$priority = DB::table('priorities')->orderBy('name', 'asc')->lists('name', 'id');
return View::make('tasks.create', array( 'client_options' => $client_options, 'status' => $status, 'priority' => $priority));
}
在我看来,我已经把它剥离到了基础上,根本没有样式,只有jquery和路由到我的控制器函数并更新链式选择的调用:
@if(count($client_options)>0)
{{ Form::select('client', $client_options, Input::old('client'), array('id' => 'select_client', 'class' => ' tempus_select')) }}
@endif
{{ Form::select('project', array_merge(array('default' => 'Select client first')), 'default', array('class' => 'tempus_select', 'id' => 'project_select')) }}
{{ HTML::script('js/jquery-2.0.3.js'); }}
<script>
$(document).ready(function($){
$('#select_client').change(function(){
$.get("/task/clientsprojects",{
option: $(this).val()
}, function(data) {
console.log(data);
var model = $('#project_select');
model.empty();
$.each(data, function(key, value) {
$('#project_select').append("<option value='"+key+"'>"+value+"</option>'");
});
$("#project_select").trigger("change");
});
});
});
</script>
然而,它输出的HTML如下:
<select id="select_client" class=" tempus_select" name="client">
<option value="0">Select a client from the list</option>
<option value="1">Client 2</option>
<option value="2">Client 1</option>
</select>
然而,在数据库中,它们具有以下值
id| client_ name |
1 | Client 1 |
2 | Client 2 |
我在getClientsProjects()
函数中做了以下调试:
'Log::info('client id = ' . $clientId);
以及我在任务控制器中的创建函数中的以下内容:
'Log::info($client_options);
他们已经返回了正确的值,但是,我知道如果我从代码中取出这个array_merge
:
$client_options = array_merge([0 => 'Select a client from the list'], $client_options);
然后值被正确加载,所以我不确定发生了什么,为什么这会导致value属性被错误加载?有人能帮我弄清楚吗,或者指定另一种插入默认值的方式?
您必须执行以下操作:
$client_options = [0=>'Select a client from the list'] + $client_options;
而不是合并。