Laravel Input Value With Select2 Not Persisting After Page Reload From Validation

- 1 answer

I have one select form input like so:

<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>

The values are empty because I'm loading with JavaScript, using the Select2 Plugin, with this:

var arrayBancos = [
    { id: 'HSBC', codigo: '399', text: 'HSBC Bank Brasil', site: '', mime: '.png' },
    { id: 'Santander', codigo: '033', text: 'Banco Santander', site: '', mime: '.png' },
    { id: 'Citibank', codigo: '745', text: 'Banco Citibank', site: '', mime: '.jpg' }

$.fn.select2.amd.require(['select2/compat/matcher'], function (oldMatcher) {
        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' }

As you can see, there are a few customizations added to the plugin (the most important one, the search looks for matches in the, arrayBancos.codigo and arrayBancos.text ), so I populated the select input with Javascript to make things easier.

Everything works fine, except one thing: When the page comes from the validation and detects an invalid input, the value of this field is not mantained (all the others are ok). Probably because there is no option values in the select yet, so it can't be set, only when the jQuery is loaded and the plugin initialized there will be options available.

So... any thoughts to work around this? Maybe set the <options> on the HTML and using data-* attributes convert to something like the array above?



On page load after you set the options in your dropdown, you should set the value of it like this:

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