Laravel - 将 Select2 默认设置为 NULL 而不是第一个选项

Mat*_*hew 1 php mysql jquery jquery-select2

我有一个 Laravel 编辑表单,它使用 Select2 jQuery 扩展以及从数据库表中提取的选项。

下面是我指的表单选择字段:

            <select id="ship_to" name="ship_to" class="js-example-basic-single2 form-control">
                @foreach($cCustomers as $customer)
                    <option value="{{$customer->id}}"
                    @if ($shipment->ship_to == $customer->id) selected="selected" 
                                 @endif
                    >{{$customer->customer_name}}</option>
                @endforeach
            </select>
Run Code Online (Sandbox Code Playgroud)

现在,一切都弹出来了,选项都在那里,选择框已转换为 Select2 格式。我的问题是,当我从数据库中提取数据时,如果特定列为空,则 select2 会提取第一个选项,而不是允许的空选择(是的,我选择了一个占位符),清除 select2 框效果很好。

所以我的问题是这样的:

如果我有一条记录,其中 select 的字段为 NULL,如何让页面自动打开,将 null 值和占位符放在 select2 框中,而不是第一个选项?

电流输出:

<select id="ship_to" name="ship_to" class="js-example-basic-single2 form-control select2-hidden-accessible" data-select2-id="ship_to" tabindex="-1" aria-hidden="true">
        <option></option>
        <option value="164" data-select2-id="387">4G ENTERPRISES</option>
        <option value="192">4G ENTERPRISES</option>
        <option value="81">5280 PACKAGING</option>
Run Code Online (Sandbox Code Playgroud)

Fra*_*erZ 6

来自文档。确保在 select2 选项上设置了一个占位符:

$('#ship_to').select2({
    placeholder: "Please select a customer"
});
Run Code Online (Sandbox Code Playgroud)

并在<select>(就在上面@foreach($cCustomers as $customer)

<option></option>
Run Code Online (Sandbox Code Playgroud)