Yii2在Gii上创建类似模型生成器的字段

时间:2016-04-18 14:47:45

标签: yii2


我试图制作一个表格字段就像" Table Name" Gii模型生成器上的字段。当用户在字段中输入时,我希望字段显示表格列中的值。

例如,如果我的表具有以下值:" Apple"," Grape"," Green Beans"," Orange&#34 ;;和G在字段中输入,列表将显示" Grape"和"青豆"。就像"表名"模型生成器的工作原理

感谢。

1 个答案:

答案 0 :(得分:1)

Gii使用http://twitter.github.io/typeahead.js/进行自动完成,对于我的项目,我选择了Select2组件(https://github.com/kartik-v/yii2-widget-select2

观看代码

echo $form->field($userCompany, 'company')->widget(Select2::classname(), [
    'options' => ['placeholder' => 'Select a company or enter new one ...'],
    'pluginOptions' => [
        'tags' => true,
        'ajax' => [
          'url' => Url::to(['/companies/index']),
          'dataType' => 'json',
          'data' => new JsExpression('function(params) { return {q:params.term}; }'),
          'processResults' => new JsExpression('function(data, params) { return { results: data.items, pagination: {more: data.more}}; }'),
        ],
    ],
]); 
?>

控制器代码

public function actionIndex($q = null, $page = null) {
    Yii::$app->response->format = Response::FORMAT_JSON;

    if ($q == null) {
        $q = "";
    }

    $q = strtr($q, ['%' => '\%', '_' => '\_', '\\' => '\\\\']) . '%';

    if (empty($page)) {
        $page = 1;
    }

    $pageSize = 50;

    $items = Company::find()
        ->select(['id', 'name as text'])
        ->where(['like', 'name', $q, false])
        ->orderBy('name ASC')
        ->limit($pageSize)
        ->offset(($page - 1) * $pageSize)
        ->asArray(true)
        ->all();

    return ['items' => $items, 'more' => (count($items) == $pageSize)];
}