SM0827 SM0827 - 3 months ago 39
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?

View:

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(''); ?>


Controller:

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


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

$profile->associationSelect
is prepopulated by the controller with a key. My problem is that the widget always shows 'Select Association ...' whether
$profile->associationSelect
is populated or not. I only want the placeholder to show if
$associationSelect
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).

Answer

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(''); ?>
Comments