【问题标题】:Is there a way to dynamically change maximumSelectionLength on kartik/select2 in yii2?有没有办法在 yii2 中动态更改 kartik/select2 上的 maximumSelectionLength?
【发布时间】:2020-05-30 23:17:12
【问题描述】:

我正在尝试根据第二个 select2 (nom_id) 的值在更改时通过 javascript 更新 select2 字段 (listeProduits) 的 maximumSelectionLength 参数。 在加载表单之前,我首先将 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

【问题讨论】:

    标签: yii2 jquery-select2 kartik-v


    【解决方案1】:

    动态设置maximumSelectionLength属性:

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

    【讨论】:

    • 感谢您的回答,但这就是我在这里所做的:"select2:select" => "function() { $('select[name =\"listeProduits[]\"]'). select2({ maximumSelectionLength: nomMaxChildren[\$(this).val()] }); }", 但这使得 select2 很窄
    猜你喜欢
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多