jquery - Yii2:如何将选项组与基于 AJAX 的 Kartik 的 Select2 一起使用

标签 jquery ajax yii2 jquery-select2 kartik-v

目前,我有一个表单字段来呈现带有基于 Kartik 的 Select2 的选项组的静态下拉列表。使用以下内容填充数据:

public function getBibliographyList()
{ 
    return ArrayHelper::map($this->find()->select(['id','title','author'])
              ->orderBy('author','title')->all(), 'id', 'title', 'author');
}

以便标题显示在各自的作者选项组下。

现在我想修改表单以利用 AJAX,所以我以 Krajee Demo Site for Select2 为例。并对其进行了如下修改:

------查看----------

<?= $form->field($model, 'orig_id')->widget(Select2::classname(), [
        'options' => ['placeholder' => Yii::t('app', 'Select a title...)],
        'pluginOptions' => [
            'allowClear'         => true,
            'minimumInputLength' => 3,
            'language'           => Yii::$app->language,
            'theme'              => 'krajee',
            'ajax' => [
                'url'      => \yii\helpers\Url::to(['search-doc']),
                'dataType' => 'json',
                'data'     => new JsExpression('function (params) { return {q:params.term}; }'),
            ],
            'errorLoading'      => new JsExpression("function () { return '".Yii::t('app', 'Waiting for data...')."'; }"),
            'escapeMarkup'      => new JsExpression("function (markup) { return markup; }"),
            'templateResult'    => new JsExpression("function (bibliography) { return bibliography.title; }"),
            'templateSelection' => new JsExpression("function (bibliography) { return bibliography.title; }"),
        ],
]) ?>

-------- Controller -------------

public function actionSearchDoc($q = null)
{
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $out = ['id' => '', 'title' => '', 'author' => ''];
    if ($q) {
        $query = new yii\db\Query;
        $query->select('id, title, author')
              ->from('bibliography')
              ->where(['like', 'title', $q])
              ->orWhere(['like', 'author', $q])
              ->limit(50);
        $command = $query->createCommand();
        $data    = $command->queryAll();
        $out = array_values($data);
    }
    return \yii\helpers\ArrayHelper::map($out, 'id', 'title', 'author');
}

根据 Kartik 的 Select2 docs , ArrayHelper::map 是当 optgroups 存在时要走的路,但我无法弄清楚这一点,因为结果下拉列表始终为空。以下是来自 ArrayHelper::map 的示例 JSON 字符串:

{"results":{"Author1":{"4":"DocumentFoo1","121":"DocumentFoo2","219":"DocumentFoo3","197":"DocumentFoo4","198":"DocumentFoo5","2":"DocumentFoo6","273":"DocumentFoo7"},"Author2":{"68":"DocumentThee1"}}}

有什么想法吗?

最佳答案

这是我自己想出来的。首先,我们必须关心提供基于 AJAX 的 Select2 所需的 JSON 字符串,它必须像这样(注意基于 AJAX 的 Select2 构建 optgroup 所需的特殊关键字 resultsidtextchildren ):

Array
(
[results] => Array
    (
        [0] => Array
            (
                [text] => "author1"
                [children] => Array
                    (
                        [0] => Array
                            (
                                [id] => "id1"
                                [text] => "title1"
                            )
                        [1] => Array
                            (
                                [id] => "id2"
                                [text] => "title2"  
                            )                           
                    )
            )
        [1] => Array
            (
                [text] => "author2"
                [children] => Array
                    (
                        [0] => Array
                            (
                                [id] => "id3"
                                [text] => "title3"
                            )
                    )
            )
    )
)

但是,四参数 ArrayHelper::map 输出如下:

Array
(
    [author1] => Array
        (
            [id1] => "title1"
            [id2] => "title2"
        )

    [author2] => Array
        (
            [id3] => "title3"
        )
)

因此,我们必须重新排列内容并合并这些特殊关键字。因此,正确的 Controller 操作应该是这样的:

public function actionSearchDoc($q = null)
{
    // JSON format result.
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $out['results'] = '';
    if ($q) {
        $query = Bibliography::find()->select(['id', 'title', 'author'])
                                     ->where(['like', 'title', $q])
                                     ->orWhere(['like', 'author', $q])
                                     ->all();
        // Group titles by author.
        $authorArray = ArrayHelper::map($query, 'id', 'title', 'author');
        // Previous array lacks keywords needed to use optgroups
        // in AJAX-based Select2: 'results', 'id', 'text', 'children'.
        // Let's insert them.
        $results = []; 
        foreach ($authorArray as $author => $docArray) {
            $docs  = [];
            foreach ($docArray as $id => $title) {
                $docs[] = ['id' => $id, 'text' => $title];
            }
            $results[] = ['text' => $author, 'children' => $docs];
        }
        $out['results'] = $results;
    }
    return $out;
}

所以,就是这样。希望对您有所帮助。

关于jquery - Yii2:如何将选项组与基于 AJAX 的 Kartik 的 Select2 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42331110/

相关文章:

javascript - 传递按钮 ID 进行发布。 js

jquery - 为什么不在 jquery .click 上应用 CSS 属性?

ajax - 链接 AJAX 请求 - Angular 2 和 ES2015 Promises

javascript switch 语句未触发

jquery - 如何使用 jQuery 获取表格单元格值

javascript - 如何将ajax响应值传递到另一个页面?

javascript - jQuery $.get() 不运行 php 脚本

php - Yii2 Active record 如何创建 mongo 模型之间的关系

Yii2 findModel 到数组

php - Yii2-查询结果数组不返回任何值