Search code examples
yii2jquery-select2-4

Select2 Krajee widget - using modal and getting the id of the value


What is the way to get the value of the select item with modal. As it is shown in demo example (Using a select2 widget inside a modal dialog):

Modal::begin([
'options' => [
    'id' => 'kartik-modal',
    'tabindex' => false // important for Select2 to work properly
],
'header' => '<h4 style="margin:0; padding:0">Select2 Inside Modal</h4>',
'toggleButton' => ['label' => 'Show Modal', 'class' => 'btn btn-lg btn-primary'],
]);


echo Select2::widget([
'name' => 'state_40',
'data' => $data,
'options' => ['placeholder' => 'Select a state ...'],
'pluginOptions' => [
    'allowClear' => true
],
]);
Modal::end();

I get the options to be shown and select, but I need id of the selected value to be saved somewhere so I can get it to be forwarded as part of the link in button.

For example:

Html::button('Example', ['value' => Url::to(['example/example', 'id' => ?]),'class' => 'btn btn-lg btn-primary ']);

Solution

  • this is a easy way. I´ve done it many times.

    'options' => [
                    'class'=>'col-md-3','id'=>'id_select',
                    'placeholder' => 'Select the country',
                 ],
    

    with jquery :

    var id_select = $('#id_select').val();
    

    Or if you prefer ajax:

          echo  Html::a('<i class="fa fa-check"></i> Send',null,[
        'class' => 'btn btn-primary',
        'title' => Yii::t('yii', 'Enviar'),
        'onclick'=>"
         var id_select = $('#id_select').val();
         $.ajax({
            type:'post',
            cache    : false,
            url  : '".Url::toRoute(['example'])."&id='+id_select,
            success  : function(response) {
              //ok      
            },
            error: function() {
              alert('Error');
            }
         });
    ]);
    

    you can´t get all parameters with php, you need client languaje for get this. However I´d invite you to use <form> with model, is more easy and fast.