繁体   English   中英

使用 laravel 在 bootstrap multi select 中预选选定的选项

[英]Pre-select selected options in bootstrap multi select with laravel

我已经在我的多选应用程序中实现了引导程序多选。 我在编辑表单中预选值时遇到问题。 下面是我用过的js代码:

<script>
    $(document).ready(function() {
            $('#tincludeds').multiselect({
            includeSelectAllOption: true,
            selectAllJustVisible: false,
            enableFiltering: true,
            numberDisplayed: 1,
            maxHeight: 600,
            buttonWidth: '400px',
            select: {!! json_encode($tour->tIncludeds()->allRelatedIds()) !!}
        });
    });
</script>

但是脚本不起作用。 有什么我在这里遗漏的吗? 下面是{{ dd(json_encode($tour->tIncludeds()->allRelatedIds())) }}

在我看来,多选字段的 Html 代码:

<div class="form-group">
    <label for="tincluded">Includeds</label>
    <select class="form-control" id="tincludeds" multiple="multiple" name="tincludeds[]" class="tincluded">
        @foreach($tincludeds as $included)
        <option value="{{ $included->id }}">{{ $included->name }}</option>t
        @endforeach   
    </select>   
    @if ($errors->has('tincludeds'))
    <span class="help-block">{{$errors->first('tincludeds')}}</span>                            
    @endif  
</div>

输出

你可以在你的代码中做这样的事情:

<?php     
    $listofIds = $tour->tIncludeds()->allRelatedIds(); // array with list of ids
?>
<div class="form-group">
    <label for="tincluded">Includeds</label>
    <select class="form-control" id="tincludeds" multiple="multiple" name="tincludeds[]" class="tincluded">
        @foreach($tincludeds as $included)
           <option value="{{ $included->id }}" <?php echo in_array($included->id, $listofIds) ? 'selected' : ''?> >{{ $included->name }}</option>
        @endforeach   
    </select>   
    @if ($errors->has('tincludeds'))
    <span class="help-block">{{$errors->first('tincludeds')}}</span>                            
    @endif  
</div>

如果$listofIds作为对象来自控制器,则需要在视图中或控制器中将其更改为数组 在控制器中:

$listofIds = Model::pluck('id')->toArray();

或者在传递给in_array()函数之前在查看$listofIds->toArray()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM