从验证重新加载页面后,Select2的Laravel输入值未持久化


Laravel input value with Select2 not persisting after page reload from validation

我有一个选择表单输入,如下所示:

<div class="form-group col-md-3 @if($errors->first('contas.0.banco')) has-error @endif">
    {!! Form::label('contas[0][banco]', 'Nome do Banco') !!}
    {{ Form::select('contas[0][banco]', [] , null , ['class' => 'form-control select-banco']) }}
    <small class="text-danger">{{ $errors->first('contas.0.banco') }}</small>
</div>

这些值是空的,因为我正在使用JavaScript加载,使用Select2插件,其中包括:

var arrayBancos = [
    { id: 'HSBC', codigo: '399', text: 'HSBC Bank Brasil', site: 'www.hsbc.com.br', mime: '.png' },
    { id: 'Santander', codigo: '033', text: 'Banco Santander', site: 'www.santander.com.br', mime: '.png' },
    { id: 'Citibank', codigo: '745', text: 'Banco Citibank', site: 'www.citibank.com.br', mime: '.jpg' }
];
$.fn.select2.amd.require(['select2/compat/matcher'], function (oldMatcher) {
    selectElement.select2({
        data: arrayBancos,
        language: 'pt-BR',
        matcher: oldMatcher(matchStart),
        escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
        templateResult: formatSelecaoBanco,
        templateSelection: formatBanco,
        dropdownCss: { 'min-width': '350px' }
    });
});

正如您所看到的,插件中添加了一些自定义项(最重要的是,搜索在arrayBancos.idarrayBancos.codigoarrayBancos.text中查找匹配项),所以我用Javascript填充了select输入,以使事情变得更容易。

一切都很好,除了一件事:当页面来自验证并检测到无效输入时,该字段的值不会被保留(其他所有字段都可以)。可能是因为select中还没有选项值,所以无法设置,只有当加载jQuery并初始化插件时,才会有可用的选项。

所以。。。对此有什么想法吗?也许可以在HTML上设置<options>,并使用data-*属性转换为类似上面的数组?

在页面加载时,在下拉列表中设置选项后,您应该这样设置它的值:

$(".select-banco").select2("val", "HSBC");