【问题标题】:how to preform a dynamic select dropdown in laravel 4如何在 laravel 4 中执行动态选择下拉菜单
【发布时间】:2013-11-11 19:09:10
【问题描述】:

我已经设置了我的项目与客户相关的关系,我想做的是能够通过下拉列表在我的创建项目视图中选择一个选项。

可以这样实现:

{{ Form::select('client', array('s' => 's', 'm' => 'm'), 's');}}

但是我不确定如何从我从数据库中检索的数据动态地执行此操作,我目前的代码是:

{{ Form::open(array('action' => 'ProjectController@store', 'id' => 'createproject')) }}
  <div class="form-group">
  <? $projects = Auth::user()->clients; ?>
@if (Auth::check())
    @if (count($projects) > 0)
   @foreach ($projects as $client)

{{ Form::select('client', array('client_one' => 'client_one', 'client_two' => 'client_two'), 'client_one');}}

   @endforeach 
   @else
    <h3>You have no projects click <a href="/project/create">here to create a project</a></h3>
@endif
@endif
</div>
<div class="form-group">
    {{ Form::label('project_name', 'Project Name') }}
    {{ Form::text('project_name', Input::old('project_name'), array('class' => 'form-control')) }}

</div>

谁能指出我如何动态填充此选择字段的方向?

提前致谢!

【问题讨论】:

  • 从哪个控制器加载此view 显示处理database 查询以获取数据的控制器代码。
  • @RCV ProjectControllerCreate 查看

标签: php laravel-4 dynamic-data html-select


【解决方案1】:

在视图中进行数据处理并不是一个好主意。您应该做的是在控制器中准备数组并在视图中使用该数组。

在您的控制器中。

    $clients = Auth::user()->clients;
$client_selector = array();

foreach($clients as $client) {
    $client_selector[$client->name] = $client->name; // I assume name attribute contains client name here
}

return View::make('your.view', array(.., 'client_selector' => $client_selector, ...));

在你看来。

@if(count($client_selector)>0)
    {{Form::select('client', $client_selector, array_values($client_selector)[0])}}
@endif 

【讨论】:

  • 谢谢!那行得通!您介意解释为什么视图中的数据处理不是一个好主意吗?只是因为我正处于个人项目的早期阶段,我想确保我的脚本符合良好的标准:)
  • 这叫做关注点分离。由于视图是表示层,它应该只执行那个任务和那个任务。更多详情请在laravelbook.com/laravel-introduction中搜索“关注点分离”
【解决方案2】:

我认为这是一个更好的解决方案:

在您的控制器中:

$clients = Auth::user()->clients->lists('name', 'name');

return View::make('your.view', array(.., 'clients' => $clients, ...));

在你看来:

    {{ Form::select('client', $clients) }}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 2019-11-11
    • 1970-01-01
    相关资源
    最近更新 更多