Newbie - problems grasping kartik's select2

I’m still trying to learn and I have what seems a huge mountain in front of me. Surely enough a stupid question.

I’m trying to implement kartik’s select2 to help searching an existing value inside a large number of entries with autosuggest functionality. here is my “cognome” (surname) field

VIEW in the _search.php

echo $form->field($model, 'cognome')->widget(Select2::classname(), [
'options' => ['placeholder' => 'Inizia a digitare il cognome ...'],
'pluginOptions' => [
    'allowClear' => true,
    'minimumInputLength' => 1,
    'language' => [
        'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"),
    ],
    'ajax' => [
        'url' => \yii\helpers\Url::to(['anagrafica\cognomelist']),
        'dataType' => 'json',
        'data' => new JsExpression('function(params) { return {q:params.term}; }')
    ],
    'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
    'templateResult' => new JsExpression('function(cognome) { return cognome.text; }'),
    'templateSelection' => new JsExpression('function (cognome) { return cognome.text; }'),
],

]);

and my AnagraficaController.php

public function actionCognomelist($q = null, $id = null) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$out = ['results' => ['id' => '', 'text' => '']];
if (!is_null($q)) {
    $query = new Query;
    $query->select('id, cognome AS text')
        ->from('anagrafica')
        ->where(['like', 'cognome', $q])
        ->limit(20);
    $command = $query->createCommand();
    $data = $command->queryAll();
    $out['results'] = array_values($data);
}
elseif ($id > 0) {
    $out['results'] = ['id' => $id, 'text' => Anagrafica::find($id)->cognome];
}
return $out;

}

I tried to stick with the ajax loading example in kartik’s site but without luck. I’m afraid there’s something wrong with the $url variable maybe?

Please be patient with me: I need to make a small project for a job application and it’s my first attempt with yii2. A free pizza for everyone helping if I’ll get the job!

I’ve tried to change the url with url’ => \yii\helpers\Url::to([’/anagrafica/cognomelist’]), as suggested by kartik himself in a different post, but no result…

What is the response of Ajax Request? Check ajax request in browser console.

jquery.js:10099 GET http://localhost/yii2/web/index.php?r=anagrafica%2Fcognomelist&q=r 500 (Internal Server Error)

and this is the detail

jquery.js:10099 GET http://localhost/yii2/web/index.php?r=anagrafica%2Fcognomelist&q=r 500 (Internal Server Error)

send @ jquery.js:10099
ajax @ jquery.js:9682
transport @ select2.full.js:3582
request @ select2.full.js:3624
AjaxAdapter.query @ select2.full.js:3661
MinimumInputLength.query @ select2.full.js:3937
(anonimo) @ select2.full.js:598
(anonimo) @ select2.full.js:5669
Observable.invoke @ select2.full.js:655
Observable.trigger @ select2.full.js:645
Select2.trigger @ select2.full.js:5827
(anonimo) @ select2.full.js:5629
Observable.invoke @ select2.full.js:655
Observable.trigger @ select2.full.js:649
Search.handleSearch @ select2.full.js:4174
(anonimo) @ select2.full.js:598
(anonimo) @ select2.full.js:4120
dispatch @ jquery.js:5429
elemData.handle @ jquery.js:5233

referring to this line of code

// Do send the request (this may raise an exception)
				xhr.send( options.hasContent && options.data || null )

Hi @MassimoB,

What do you find in runtime/logs/app.log ? The application log should give you some hint.

2021-02-01 22:59:45 [::1][100][l4ia2oh80gt85ketiq5ovn254n][error][Error] Error: Class ‘app\controllers\Query’ not found in C:\xampp\htdocs\yii2\controllers\AnagraficaController.php:150
Stack trace:
#0 [internal function]: app\controllers\AnagraficaController->actionCognomelist(‘r’, NULL)
#1 C:\xampp\htdocs\yii2\vendor\yiisoft\yii2\base\InlineAction.php(57): call_user_func_array(Array, Array)
#2 C:\xampp\htdocs\yii2\vendor\yiisoft\yii2\base\Controller.php(181): yii\base\InlineAction->runWithParams(Array)
#3 C:\xampp\htdocs\yii2\vendor\yiisoft\yii2\base\Module.php(534): yii\base\Controller->runAction(‘cognomelist’, Array)
#4 C:\xampp\htdocs\yii2\vendor\yiisoft\yii2\web\Application.php(104): yii\base\Module->runAction(‘anagrafica/cogn…’, Array)
#5 C:\xampp\htdocs\yii2\vendor\yiisoft\yii2\base\Application.php(392): yii\web\Application->handleRequest(Object(yii\web\Request))
#6 C:\xampp\htdocs\yii2\web\index.php(12): yii\base\Application->run()
#7 {main}
2021-02-01 22:59:45 [::1][100][l4ia2oh80gt85ketiq5ovn254n][info][application] $_GET = [
‘r’ => ‘anagrafica/cognomelist’
‘q’ => ‘r’
]

$_POST = []

$_FILES = []

$_COOKIE = [
‘PHPSESSID’ => ‘l4ia2oh80gt85ketiq5ovn254n’
‘_csrf’ => ‘6d67b36ab4d76ab181342614d15a5cfc29733b1db8837e3419516851f6ca2174a:2:{i:0;s:5:"_csrf";i:1;s:32:“104RpWUdk5WhSEquiWe_JsuYujabOwtm”;}’
]

$_SESSION = [
‘__flash’ => []
‘__captcha/site/captcha’ => ‘iuxaqzu’
‘__captcha/site/captchacount’ => 1
‘__id’ => ‘100’
]

$_SERVER = [
‘MIBDIRS’ => ‘C:/xampp/php/extras/mibs’
‘MYSQL_HOME’ => ‘\xampp\mysql\bin’
‘OPENSSL_CONF’ => ‘C:/xampp/apache/bin/openssl.cnf’
‘PHP_PEAR_SYSCONF_DIR’ => ‘\xampp\php’
‘PHPRC’ => ‘\xampp\php’
‘TMP’ => ‘\xampp\tmp’
‘HTTP_HOST’ => ‘localhost’
‘HTTP_CONNECTION’ => ‘keep-alive’
‘HTTP_ACCEPT’ => ‘application/json, text/javascript, /; q=0.01’
‘HTTP_X_CSRF_TOKEN’ => ‘zY4LSQUgzELoITGZdUfJ1a6yTx9hypCvCW0eScCR-Rf8vj8bdXeZJoMUZvEmArigx-UqQCu55fZ8B38rj-aNeg==’
‘HTTP_USER_AGENT’ => ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36 Edg/88.0.705.56’
‘HTTP_X_REQUESTED_WITH’ => ‘XMLHttpRequest’
‘HTTP_SEC_FETCH_SITE’ => ‘same-origin’
‘HTTP_SEC_FETCH_MODE’ => ‘cors’
‘HTTP_SEC_FETCH_DEST’ => ‘empty’
‘HTTP_REFERER’ => ‘http://localhost/yii2/web/index.php?r=anagrafica%2Fricerca
‘HTTP_ACCEPT_ENCODING’ => ‘gzip, deflate, br’
‘HTTP_ACCEPT_LANGUAGE’ => ‘it,it-IT;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6’
‘HTTP_COOKIE’ => ‘PHPSESSID=l4ia2oh80gt85ketiq5ovn254n; _csrf=6d67b36ab4d76ab181342614d15a5cfc29733b1db8837e3419516851f6ca2174a%3A2%3A%7Bi%3A0%3Bs%3A5%3A%22_csrf%22%3Bi%3A1%3Bs%3A32%3A%22104RpWUdk5WhSEquiWe_JsuYujabOwtm%22%3B%7D’
‘PATH’ => ‘C:\Program Files\Common Files\Oracle\Java\javapath;C:\Program Files\ImageMagick-7.0.10-Q16-HDRI;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\xampp\php;C:\xampp\php;C:\ProgramData\ComposerSetup\bin;C:\Program Files\Git\cmd;C:\Users\elfoc\AppData\Local\Microsoft\WindowsApps;C:\Users\elfoc\AppData\Roaming\Composer\vendor\bin;C:\Users\elfoc\AppData\Local\GitHubDesktop\bin’
‘SystemRoot’ => ‘C:\WINDOWS’
‘COMSPEC’ => ‘C:\WINDOWS\system32\cmd.exe’
‘PATHEXT’ => ‘.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC’
‘WINDIR’ => ‘C:\WINDOWS’
‘SERVER_SIGNATURE’ => 'Apache/2.4.46 (Win64) OpenSSL/1.1.1h PHP/7.4.14 Server at localhost Port 80

‘SERVER_SOFTWARE’ => ‘Apache/2.4.46 (Win64) OpenSSL/1.1.1h PHP/7.4.14’
‘SERVER_NAME’ => ‘localhost’
‘SERVER_ADDR’ => ‘::1’
‘SERVER_PORT’ => ‘80’
‘REMOTE_ADDR’ => ‘::1’
‘DOCUMENT_ROOT’ => ‘C:/xampp/htdocs’
‘REQUEST_SCHEME’ => ‘http’
‘CONTEXT_PREFIX’ => ‘’
‘CONTEXT_DOCUMENT_ROOT’ => ‘C:/xampp/htdocs’
‘SERVER_ADMIN’ => ‘postmaster@localhost’
‘SCRIPT_FILENAME’ => ‘C:/xampp/htdocs/yii2/web/index.php’
‘REMOTE_PORT’ => ‘62764’
‘GATEWAY_INTERFACE’ => ‘CGI/1.1’
‘SERVER_PROTOCOL’ => ‘HTTP/1.1’
‘REQUEST_METHOD’ => ‘GET’
‘QUERY_STRING’ => ‘r=anagrafica%2Fcognomelist&q=r’
‘REQUEST_URI’ => ‘/yii2/web/index.php?r=anagrafica%2Fcognomelist&q=r’
‘SCRIPT_NAME’ => ‘/yii2/web/index.php’
‘PHP_SELF’ => ‘/yii2/web/index.php’
‘REQUEST_TIME_FLOAT’ => 1612216785.012
‘REQUEST_TIME’ => 1612216785
]

Query should refer to yii\db\Query.

if (!is_null($q)) {
    // $query = new Query;
    $query = new yii\db\Query;
    $query->select('id, cognome AS text')
        ->from('anagrafica')
        ->where(['like', 'cognome', $q])
        ->limit(20);

now i have a 404 error
yii\web\HttpException:404 yii\base\InvalidRouteException: Unable to resolve the request: anagrafica/\anagrafica\cognomelist in C:\xampp\htdocs\yii2\vendor\yiisoft\yii2\base\Controller.php:152
Stack trace:
#0 C:\xampp\htdocs\yii2\vendor\yiisoft\yii2\base\Module.php(534): yii\base\Controller->runAction(’\anagrafica\cog…’, Array)
#1 C:\xampp\htdocs\yii2\vendor\yiisoft\yii2\web\Application.php(104): yii\base\Module->runAction(‘anagrafica/\ana…’, Array)
#2 C:\xampp\htdocs\yii2\vendor\yiisoft\yii2\base\Application.php(392): yii\web\Application->handleRequest(Object(yii\web\Request))
#3 C:\xampp\htdocs\yii2\web\index.php(12): yii\base\Application->run()
#4 {main}

Next yii\web\NotFoundHttpException: Page not found. in C:\xampp\htdocs\yii2\vendor\yiisoft\yii2\web\Application.php:116
Stack trace:
#0 C:\xampp\htdocs\yii2\vendor\yiisoft\yii2\base\Application.php(392): yii\web\Application->handleRequest(Object(yii\web\Request))
#1 C:\xampp\htdocs\yii2\web\index.php(12): yii\base\Application->run()
#2 {main}

trying to change the $url value in the view to simply ‘url’ => \yii\helpers\Url::to([‘cognomelist’]),

trows me again a 500 error

Error: Class 'Yii\db\Query' not found in C:\xampp\htdocs\yii2\controllers\AnagraficaController.php:150

Stack trace:
#0 [internal function]: app\controllers\AnagraficaController->actionCognomelist(‘r’, NULL)
#1 C:\xampp\htdocs\yii2\vendor\yiisoft\yii2\base\InlineAction.php(57): call_user_func_array(Array, Array)
#2 C:\xampp\htdocs\yii2\vendor\yiisoft\yii2\base\Controller.php(181): yii\base\InlineAction->runWithParams(Array)
#3 C:\xampp\htdocs\yii2\vendor\yiisoft\yii2\base\Module.php(534): yii\base\Controller->runAction(‘cognomelist’, Array)
#4 C:\xampp\htdocs\yii2\vendor\yiisoft\yii2\web\Application.php(104): yii\base\Module->runAction(‘anagrafica/cogn…’, Array)
#5 C:\xampp\htdocs\yii2\vendor\yiisoft\yii2\base\Application.php(392): yii\web\Application->handleRequest(Object(yii\web\Request))
#6 C:\xampp\htdocs\yii2\web\index.php(12): yii\base\Application->run()
#7 {main}

So i managed to find that I haven’t imported the query class!

The answer was that. By the way thanks for the support. Now I know a little better how to track for error from the error messages!
Give a slice of pizza to this man!

1 Like

Congrats!

Do you need the addresses of @InsaneSkull and me?

2 Likes