Denis H
Denis H

Reputation: 11

yii2-select2 matcher in yii2 kartik widget

I'm using yii2-select2 kartik widget for cities, but the search for cities work horrible, because firstly it's seeking inside the word but i would like to seek first latter firstly. For example i put letter K, and it should find a words which started on word K but unfortunately it found firstly inside the word.

In base jquery select2 there is solve of this problem: enter link description here

But how can i add it to this widget:enter link description here

Upvotes: 1

Views: 751

Answers (2)

Alex
Alex

Reputation: 553

You can write your own solution inside matchCustom function.

Here is a full example.

P.S. Code was taken from CPUBOSS:

<?php
$script = <<< JS
    function matchCustom(params, data) {
        // If there are no search terms, return all of the data
        if (typeof params.term === 'undefined' || params.term.trim().length === 0) {
            return data;
        }

        // Do not display the item if there is no 'text' property
        if (typeof data.text === 'undefined') {
            return null;
        }


        // `params.term` should be the term that is used for searching
        // `data.text` is the text that is displayed for the data object
        const termLo = params.term.trim().toLowerCase().split(' ');
        const textLo = data.text.trim().toLowerCase();
        let allIncludes = true;
        for (let i = 0; i < termLo.length; i++) {
            if (!textLo.includes(termLo[i])){
                allIncludes = false;
                break;
            }
        }
        if (allIncludes) {
            //var modifiedData = $.extend({}, data, true);
            //modifiedData.text += ' (matched)';

            // You can return modified objects from here
            // This includes matching the `children` how you want in nested data sets
            //return modifiedData;

            return data;
        }

        // Return `null` if the term should not be displayed
        return null;
    }
JS;

$this->registerJs($script, $this::POS_HEAD);
?>

<?= $form->field($model, 'product_id')->widget(Select2::class, [
    'data' => $items,
    'options' => [
        'placeholder' => 'Select item...',
        'multiple' => false,
    ],
    'pluginOptions' => [
        'allowClear' => true,
        'matcher' => new JsExpression('matchCustom'),
        // 'minimumInputLength' => 1,
    ],
    'theme' => Select2::THEME_KRAJEE_BS3
]); ?>

Upvotes: 0

vityapro
vityapro

Reputation: 198

Did you try use pluginOptions attribute?

$match = <<< SCRIPT
function matchStart (term, text) {
    if (text.toUpperCase().indexOf(term.toUpperCase()) == 0) {
    return true;
  }
  return false;
}
SCRIPT;
echo Select2::widget([
    'name' => 'cities',
    'data' => $data,
    'options' => ['placeholder' => 'Select a city...'],
    'pluginOptions' => [
        'matcher' => new JsExpression('match'),
    ],
]);

Upvotes: 2

Related Questions