您好我尝试在动态选择中实现默认占位符,该占位符链接到另一个选择。我正在使用存储库来查询数据库以检索加载到第一个选择中的users
clients
。第二个选择是一个链式选择,它有一个占位符,易于实现。无论如何,我尝试了以下内容,但它在select选项的value属性中加载了错误的ID。
我正在获取auth用户客户端,然后客户端项目就像我的存储库中那样:
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);
以及我在任务控制器中的create函数中的以下内容:
\Log::info($client_options);
并且他们返回了正确的值,但是,我知道如果我从代码中取出array_merge
:
$client_options = array_merge([0 => 'Select a client from the list'], $client_options);
然后正确加载值,所以我不确定发生了什么,为什么会导致value属性被错误加载?有人可以帮我解决这个问题,或者可能指定另一种插入默认值的方法吗?
答案 0 :(得分:1)
你必须这样做:
$client_options = [0=>'Select a client from the list'] + $client_options;
而不是合并。