I just added hidden inputs and every time the select2 changes I put the value in the input. When the page comes from validation or whatever, I just iterate through the inputs and put the value on the select.
Select2 value not persisting after page reload from validation
Hi there,
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 is 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?
Please or to participate in this conversation.