【问题标题】:Pre-select selected options in bootstrap multi select with laravel使用 laravel 预选引导多选中的选定选项
【发布时间】:2018-04-11 06:14:30
【问题描述】:

我在我的多选应用程序中实现了bootstrap multi-select。我在编辑表单中预选值时遇到问题。下面是我用过的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-&gt;tIncludeds()-&gt;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>

【问题讨论】:

  • 你的json一定有错误
  • json_encode($tour-&gt;tExcludeds()-&gt;allRelatedIds()) 是正确的我已经用 dump and die dd() 方法检查了它。
  • 能否请您显示您的多选下拉菜单的 HTML/Laravel 代码?
  • 能否附上 allRelatedIds 函数的输出?
  • 也许我遗漏了一些东西,但我没有在他们的手册中看到多选插件的“选​​择”参数。

标签: javascript php jquery twitter-bootstrap laravel


【解决方案1】:

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

<?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-&gt;toArray()

【讨论】:

  • 与您的 sn-p 我收到错误消息 in_array() expects parameter 2 to be array, object given
  • @TanjaForsberg $listofIds 应该是一个数组。您可以简单地打印并检查它是否存在
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-10
  • 1970-01-01
  • 1970-01-01
  • 2011-07-10
  • 2014-09-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多