How does a select2 widget gets populated with AJAX

2019-04-13 07:58发布

问题:

When I enter a few characters in my widget, I get results like these from AJAX:

[{"id":550,"campName":"IB Resi Showtime Rebate Website"},{"id":60,"campName":"OB ACGBK EB"}]

However, I'm missing the part on how to populate the widget with those results.

Here is the code I use for the widget:

$this->widget
(
        'ext.ESelect2-master.ESelect2',
        [
            'selector'=>'#campaigns',
            'options'=>
            [
                'tags'=>$tags,
                'allowClear'=>true,
                'minimumInputLength' => 2,
                'width'=>'300px',
                'multiple'=>true,
                'placeholder'=>'Campaigns',
                'ajax'=>
                [
                    'url'=>Yii::app()->createUrl('CoxReports/autoCompleteCampaigns'),
                    'dataType'=>'json',
                    'data'=>'js:function(term,page){return{q: term, page_limit: 10, page: page};}',
                    'results'=>'js:function(data,page){ return {results:data};}'
                ]
            ]
        ]
);

What am I missing?

回答1:

You're missing a formatResult and a formatSelection definition in your widget. See this code for an example.

The results are handled by the formatResult function with custom markup, the structure is similar to yours.