2017-02-19 75 views
0

В настоящее время у меня есть поле формы для отображения статического раскрывающегося списка с группами опций на основе Select2. Данные заселяются следующим образом:Yii2: Как использовать группы опций с помощью Kartik на основе AJAX 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'); 
} 

согласно выбор2 Картик в docs, ArrayHelper :: карта путь идти, когда вокруг нет групп, но я не могу Извлеките это, поскольку выпадающее меню всегда пустое. Вот пример строки JSON от ArrayHelper :: map:

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

Любые идеи?

+0

Вы не можете внести ошибку? – marche

+0

мммм, я пропустил обратную косую черту в начале строки ArrayHelper и, следовательно, эту ошибку. Во всяком случае, проблема отображения групп опций сохраняется. Я буду продолжать, пока не смогу опубликовать правильное решение. –

ответ

1

Я понял это сам. Во-первых, мы должны заботиться о необходимой строки JSON кормить AJAX на основе ВЫБ.2, который должен быть, как это (уведомление специальных ключевых слов results, id, text и children требует AJAX на основе выбор2 построить optgroups):

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" 
     ) 
) 

Таким образом, мы должны изменить вещи и включать эти специальные ключевые слова. Следовательно, надлежащее действие контроллера должно быть таким:

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; 
} 

Так вот, вот и все. Надеюсь, поможет.