Laravel blade 形式 select 语句具有值索引

Laravel blade form select statement has index for value

经过搜索并尝试解决这个问题,我似乎无法解决。

我在 class 中有一个简单的静态方法,即 returns 选项列表。我正在使用它来填充表单中的 select 元素。这工作正常,但我使用 Laravel blade 快捷方式语言,每个选项的值作为数组的索引出现,在持久化表单结果时发送到数据库:

{!! Form::select('type', \App\Http\Utilities\Airporttype::all(), null, ['class' => 'form-control'] ) !!}

HTML出品:

<select class="form-control" id="type" name="type">
<option value="0">Commercial</option>
<option value="1" selected="selected">Military</option>
<option value="2">Galactic</option><option value="3">Private</option>
</select>

调用的静态方法:

class Airporttype
{
protected static $types = [
    "Commercial",
    "Military",
    "Galactic",
    "Private",
];
public static function all()
{
    return static::$types;
}
}

通过使用 'null' 选项,如果数据库与已为该记录保存的内容匹配,它将给我选项 = selected。

我可以通过以下方式实现它,但我想使用 blade 短代码样式,因为它很干净(下面是我在其他地方以 te 形式测试过的并且有效):

<select id="country" name="country" class="form-control">
    @foreach (\App\Http\Utilities\Country::all() as $country => $code) 
        <option value="{{ $country }}" @if ($country == $airport->country) selected = 'selected' @endif>{{ $country }}</option>
    @endforeach
</select>


 Array dump of Aiporttype::all();
array (size=4)
  0 => string 'Commercial' (length=10)
  1 => string 'Military' (length=8)
  2 => string 'Galactic' (length=8)
  3 => string 'Private' (length=7)

谢谢

如果我没理解错的话,你需要这样的东西:

{!! Form::select('type', \App\Http\Utilities\Airporttype::all(), $airport->country, ['class' => 'form-control'] ) !!}

更新:

如果您有字符串类型,您可以尝试将数组更改为:

protected static $types = [
    'commercial => 'Commercial',
    'military' => 'Military',
    'galactic' => 'Galactic',
    'private' => 'Private',
];

要获取按其值索引的数组,您可以尝试这样的操作

$types = \App\Http\Utilities\Airporttype::all();

$types = array_combine($types, $types);

-- view --

{!! Form::select('type', $types, null, ['class' => 'form-control'] ) !!}

对我来说工作得很好... 在控制器中

View::share('types',\App\Http\Utilities\Airporttype::all());

在视图中

{!! Form::select('types',array(''=>'- Select types -')+$types,Input::get('types',null),array('class'=>'form-control')) !!}

您可以在php中使用array_flip功能:

{!! Form::select('type', array_flip(\App\Http\Utilities\Airporttype::all()), $airport->country, ['class' => 'form-control'] ) !!}

简单优雅的功能!