Laravel-4如何从id值和名称值的数据库中填充选择框

001*_*221 11 php select laravel laravel-4

我想clients在项目控制器中使用我的数据库填充选择框,因为项目将属于a client但它也属于登录的用户.

我想创建一个如下所示的选择框:

<select>
  <option value="$client->client_id">$client->client_name</option>
  <option value="$client->client_id">$client->client_name</option>
</select>
Run Code Online (Sandbox Code Playgroud)

我在laravel中使用客户端名称填充我的选择字段但是该value属性具有客户端名称,我宁愿这有client_id.

我这样做的方式如下:

ProjectController.php

public function create()
{
    //find logged in users clients
     $clients = Auth::user()->clients;
    $client_selector = array();
    foreach($clients as $client) {
    $client_selector[$client->client_name] = $client->client_name;
    }        
        // load the create form (app/views/projects/create.blade.php)
    return View::make('projects.create', array('client_selector' => $client_selector));
}
Run Code Online (Sandbox Code Playgroud)

create.blade.php

{{ Form::open(array('action' => 'ProjectController@store', 'id' => 'createproject')) }}
  <div class="form-group">
 @if(count($client_selector)>0)

   {{ Form::label('select_client', 'Select Client', array('class' => 'awesome'));   }}

   <!-- SELECT IS CREATED HERE -->
   {{Form::select('client', $client_selector, array_values($client_selector)[0])}}

 @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>
Run Code Online (Sandbox Code Playgroud)

从正在创建选择的方式中可以看出,它使用client_name来填充值属性,而且我不是Laravel的专家,所以我不确定如何更改这些属性.

如果有任何可能告诉我如何做到这一点或有更好的方法来实现这一点,那么请给我一些例子!

提前致谢.

001*_*221 25

找到了一种方法来做到这一点

ClientController.php

public function create() {

  // queries the clients db table, orders by client_name and lists client_name and id
  $client_optons = DB::table('clients')->orderBy('client_name', 'asc')->lists('client_name','id');

    return View::make('projects.create', array('client_options' => $client_options));
}
Run Code Online (Sandbox Code Playgroud)

create.blade.php

// this form is now populated with the value as id and the option names as the client_name
{{ Form::select('clients', $client_options , Input::old('clients')) }}
Run Code Online (Sandbox Code Playgroud)

希望这有助于其他人遇到这样的问题.

  • 按名称直接调用表不是一种不好的做法吗? (2认同)