I want to display more than 1 information when searching, so I use select2 ajax & templates. It use json. I change the url and I make function on my controller. But I have a problem. It can not show anything. What’s the problem? This is my code: view
Script
$formatJs = <<< 'JS'
var formatProduct = function (product) {
if (product.loading) {
return product.text;
}
var markup =
'<div class="row">' +
'<div class="col-sm-5">' +
'<b style="margin-left:5px">' + product.name + '</b>' +
'</div>' +
'<div class="col-sm-3"><i class="fa fa-code-fork"></i> ' + product.ean_no + '</div>' +
'<div class="col-sm-3"><i class="fa fa-star"></i> ' + product.desc + '</div>' +
'</div>';
return '<div style="overflow:hidden;">' + markup + '</div>';
};
var formatProductSelection = function (product) {
return product.name || product.text;
}
JS;
// Register the formatting script
$this->registerJs($formatJs, \yii\web\View::POS_HEAD);
// script to parse the results into the format expected by Select2
$resultsJs = <<< JS
function (data, params) {
params.page = params.page || 1;
return {
// Change `data.items` to `data.results`.
// `results` is the key that you have been selected on
// `actionJsonlist`.
results: data.results
};
}
JS;
Select2
echo Select2::widget([
'name' => 'kv-repo-template',
'value' => '14719648',
'initValueText' => 'kartik-v/yii2-widgets',
'options' => ['placeholder' => 'Search for a repo ...'],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 1,
'ajax' => [
'url' => Url::to(['/bom/product/productlist']),
'dataType' => 'json',
'delay' => 250,
'data' => new JsExpression('function(params) { return {q:params.term, page: params.page}; }'),
'processResults' => new JsExpression($resultsJs),
'cache' => true
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('formatProduct'),
'templateSelection' => new JsExpression('formatProductSelection'),
],
]);
COntroller
public function actionProductlist($search = NULL, $code = NULL)
{
header('Content-type: application/json');
$clean['more'] = false;
$query = new \yii\db\Query;
if(!is_Null($search))
{
$mainQuery = $query->select('code, name, description, volume')
->from('product');
$command = $mainQuery->createCommand();
$rows = $command->queryAll();
$clean['results'] = array_values($rows);
}
else
{
if(!is_null($code))
{
$clean['results'] = ['ean_no'=> $code, 'name' => Product::find($code)->nama,
'description' => Product::find($code)->description, 'volume' => Product::find($code)->volume];
}else
{
$clean['results'] = ['ean_no' => 123, 'name' => 'None found', 'description' => 'None found', 'volume' => 'None found'];
}
}
echo \yii\helpers\Json::encode($clean);
exit();
}