首页 > 解决方案 > 有没有办法在 yii2 中动态更改 kartik/select2 上的 maximumSelectionLength?

问题描述

我试图通过javascript更新select2字段(listeProduits)的maximumSelectionLength参数,基于第二个select2(nom_id)更改时的值。在加载表单之前,我首先将 maxChildren 值存储在 js 表中,以便在选择新的 nom_id 时可以在客户端访问它。下面的方法不起作用,因为它弄乱了 listeProduits select2。

<script>
var nomMaxChildren = <?= json_encode(ArrayHelper::map(Nom::find()->asArray()->where(['type' => 'Boite'])->all(), 'id', 'max_children')); ?>;
alert(nomMaxChildren[1]);
</script>
<?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'nom_id')->widget(Select2::classname(), [
    'data' => ArrayHelper::map(Nom::find()->asArray()->where(['type' => 'Boite'])->all(), 'id', 'nom'),
    'options' => ['placeholder' => Yii::t('app','Select a name...')],
    'pluginEvents' => [
       "select2:select" => "function() { 
            $('select[name =\"listeProduits[]\"]').select2({
                maximumSelectionLength: nomMaxChildren[\$(this).val()]
            });
       }",
    ]
]);?>

<label class="control-label"><?= Yii::t('app', 'Produits')?></label>';

<?= Select2::widget([
    'attribute' => 'listeProduits',
    'name' => 'listeProduits',
    'data' => ArrayHelper::map(Produit::find()->asArray()->where(['statut_id' => 2])->andWhere(['boite_id' => null])->orWhere(['boite_id' => $model->id])->all(), 'id', 'numero_de_serie'),
    'value' => (is_null($model->id)) ? null : ArrayHelper::map(Produit::find()->asArray()->where(['boite_id' => $model->id])->all(), 'id', 'id'),
    'options' => ['placeholder' => Yii::t('app','Select products')],
    'pluginOptions' => [
        'allowClear' => true,
        'multiple' => true,
        'maximumSelectionLength' => (isset($model->nom)) ? $model->nom->max_children : null,
    ],
    'showToggleAll' => false,
]);?>

此外,如果您对如何验证 maximumSelectionLength 在客户端是可以的这一事实有任何想法,那就太好了:D

标签: yii2jquery-select2kartik-v

解决方案


动态设置maximumSelectionLength属性:

$('#demo-select').select2({ maximumSelectionLength: 1 });

推荐阅读