Claudson Martins
Claudson Martins

Reputation: 348

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

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

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: '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' }
    });
});

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.id, 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?

Upvotes: 1

Views: 1239

Answers (1)

Adam
Adam

Reputation: 3518

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");

Upvotes: 1

Related Questions