AceVez
AceVez

Reputation: 301

Yii2 Creating Field Like Model Generator on Gii


I'm trying to make a form field just like "Table Name" field on Gii's Model Generator. I want the field to show values from a table column when user is typing in the field.

For example if my table have these values: "Apple", "Grape", "Green Beans", "Orange"; and G is typed in the field, a list will shows "Grape" and "Green Beans". Just like how the "Table Name" field on Model Generator works.

Thanks.

Upvotes: 1

Views: 108

Answers (1)

Gramotei
Gramotei

Reputation: 1554

Gii uses http://twitter.github.io/typeahead.js/ for autocompletion, for my project I've chosen Select2 component ( https://github.com/kartik-v/yii2-widget-select2 )

Code for view

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}}; }'),
        ],
    ],
]); 
?>

Code for controller

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)];
}    

Upvotes: 1

Related Questions