SM0827 SM0827 - 2 months ago 20
PHP Question

Yii2 kartik-v select2 widget allowClear and placeholder not working properly

I'm using the advanced template of Yii2. Whenever the select2 'placeholder' is assigned a value, the widget won't show the initial value. I can work around this by using

['placeholder' => $placeholder]
and setting the variable to NULL whenever an initial value exists. However, if the placeholder is NULL and an initial value is showing, then allowClear doesn't work. What am I doing wrong?


use kartik\select2\Select2;

<?= $form->field($profile, 'associationSelect')->widget(Select2::classname(), [
'data' => $associationList,
'language' => 'en',
'theme' => 'krajee',
'options' => ['placeholder' => 'Select Association ...'],
'pluginOptions' => ['allowClear' => true],
])->label(''); ?>


$associationArray = Association::find()
->select('association, id')
$associationList = ArrayHelper::map($associationArray, 'id', 'association');

$associationList is an array like {[1]=>"association1", [2]=>"association2, [3] ..."}.

is prepopulated by the controller with a key. My problem is that the widget always shows 'Select Association ...' whether
is populated or not. I only want the placeholder to show if
is empty, as that's how a placeholder is supposed to work. And if I leave placeholder empty (NULL), the clear option ("x") shows up in the widget, but won't clear the text (i.e. it doesn't do anything when clicked).


The problem is that 'associationSelect' is an internal attribute rather than a db attribute. I switched to a db attribute and it works just fine.

<?= $form->field($profile, 'association')->widget(Select2::classname(), [                         
    'data' => ArrayHelper::map(Association::find()->orderBy('id')->all(), 'id', 'association'),
    'language' => 'en',
    'theme' => 'krajee',
    'options' => ['placeholder' => 'Select ...',],
    'pluginOptions' => ['allowClear' => true],
])->label(''); ?>