0

I am using a Select2 widget:

<?php echo $form->field($model, 'id_person')->widget(
    \common\widgets\Select2::classname(),
    [
        'items' => \yii\helpers\ArrayHelper::map(\app\models\Persons::find()->all(), 'id_person', 'name_person'),
        'placeholder' => '',
        'class' => 'form-control',
        'options' => [
            'id' => 'idPerson' // For jQuery.
        ]
    ]
)
?>

Then I use jQuery to disable it and set a value as I read in this StackOverflow question:

function($) {    
    $("#idPerson").prop("disabled", true)
        .select2('data', {id: 1, a_key: 'John'});
});

It properly disabled the Select2 but the value is not set so the controller doesn't received the value.

Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
Roby Sottini
  • 2,117
  • 6
  • 48
  • 88

2 Answers2

1

the disabled inputs will not be submitted. check this: values of disabled inputs will not be submitted?. Maybe you can use "readonly" instead of disabling the input: http://demos.krajee.com/widget-details/select2#settings

0

If you are using the kartik-v\select2 widget then you need to know that it is using Version 4.0 of the plugin select2.

For the versions, >=4.0 its made simpler and you need to set options as selected using .val() and use .trigger() to actually make the options change visible, you need to look at 2 things that you can trigger the change or change.select2

  • change Causes all attached change events to trigger, including select2.
  • change.select2 Causes only select2 change event to trigger.

You need to change the line in your code to the following

$("#idPerson").val(1).trigger('change');

See here for the more detailed example on How to Add, Select or Clear.

Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68