PHP code example of 2amigos / yii2-type-ahead-widget
1. Go to this page and download the library: Download 2amigos/yii2-type-ahead-widget library. Choose the download type require. 2. Extract the ZIP file and open the index.php. 3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
2amigos / yii2-type-ahead-widget example snippets
namespace frontend\controllers\actions;
use yii\base\Action;
use yii\helpers\Json;
use yii\base\InvalidConfigException;
class AutocompleteAction extends Action
{
public $tableName;
public $field;
public $clientIdGetParamName = 'query';
public $searchPrefix = '';
public $searchSuffix = '%';
public function init()
{
if($this->tableName === null) {
throw new InvalidConfigException(get_class($this) . '::$tableName must be defined.');
}
if($this->field === null) {
throw new InvalidConfigException(get_class($this) . '::$field must be defined.');
}
parent::init();
}
public function run()
{
$value = $this->searchPrefix . $_GET[$this->clientIdGetParamName] . $this->searchSuffix;
$rows = \Yii::$app->db
->createCommand("SELECT {$this->field} AS value FROM {$this->tableName} WHERE {$this->field} LIKE :field ORDER BY {$this->field}")
->bindValues([':field' => $value])
->queryAll();
echo Json::encode($rows);
}
}
public function actions()
{
return [
'autocomplete' => [
'class' => 'frontend\controllers\actions\AutocompleteAction',
'tableName' => Country::tableName(),
'field' => 'name'
]
];
}