Laravel 4.2
@SamMonk 给出了最好的选择,我按照他的例子构建了最后一段代码
<select class="chosen-select" multiple="multiple" name="places[]" id="places">
@foreach($places as $place)
<option value="{{$place->id}}" @foreach($job->places as $p) @if($place->id == $p->id)selected="selected"@endif @endforeach>{{$place->name}}</option>
@endforeach
</select>
在我的项目中,我将有很多这样的表关系,所以我写了一个扩展来保持它的整洁。要加载它,请将其放入“app/start/global.php”之类的配置文件中。我在“app/”目录下创建了一个文件“macros.php”,并将其包含在 global.php 的 EOF 中
// app/start/global.php
require app_path().'/macros.php';
// macros.php
Form::macro("chosen", function($name, $defaults = array(), $selected = array(), $options = array()){
// For empty Input::old($name) session, $selected is an empty string
if(!$selected) $selected = array();
$opts = array(
'class' => 'chosen-select',
'id' => $name,
'name' => $name . '[]',
'multiple' => true
);
$options = array_merge($opts, $options);
$attributes = HTML::attributes($options);
// need an empty array to send if all values are unselected
$ret = '<input type="hidden" name="' . HTML::entities($name) . '[]">';
$ret .= '<select ' . $attributes . '>';
foreach($defaults as $def) {
$ret .= '<option value="' . $def->id . '"';
foreach($selected as $p) {
// session array or passed stdClass obj
$current = @$p->id ? $p->id: $p;
if($def->id == $current) {
$ret .= ' selected="selected"';
}
}
$ret .= '>' . HTML::entities($def->name) . '</option>';
}
$ret .= '</select>';
return $ret;
});
用法
没有预选项目的列表(创建视图)
{{ Form::chosen('places', $places, Input::old('places')) }}
预选(编辑视图)
{{ Form::chosen('places', $places, $job->places) }}
完整使用
{{ Form::chosen('places', $places, $job->places, ['multiple': false, 'title': 'I\'m a selectbox', 'class': 'bootstrap_is_mainstream']) }}