Introduction ¶
In this tutorial i will explain how to use jui auto complete in yii2. The Autocomplete widget enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.
Requirements ¶
To use jui auto complete widget first add
"yiisoft/yii2-jui": "^2.0"
inside your composer.json file and then update composer (using the code
php composer.phar update
)
Usage ¶
consider a scenario where you have a table named family and it contains fileds id & name. In the form you want to have the names of different families to be autocompleted.
Now inside yii2 form
<?php
use yii\jui\AutoComplete;
use yii\web\JsExpression;
$data = Family::find()
->select(['name as value', 'name as label','id as id'])
->asArray()
->all();
echo 'Family Name' .'<br>';
echo AutoComplete::widget([
'clientOptions' => [
'source' => $data,
'minLength'=>'3',
'autoFill'=>true,
'select' => new JsExpression("function( event, ui ) {
$('#memberssearch-family_name_id').val(ui.item.id);//#memberssearch-family_name_id is the id of hiddenInput.
}")],
]);
?>
Forgot something
also add the field where you want the autocomplete value to appear
<?= Html::activeHiddenInput($model, 'family_name_id')?>
id of this field is what we use inside the jsExpression
:(
Your tutorial is bad for now.
count($data)
<= 20 by default$('#memberssearch-family_name_id')
can be calculate from $model->formName...
I don't understand
I read from this documentation but couldn't find anough information to understand how the widget works; Can you help me understand those properties:
$('#memberssearch-family_name_id').val(ui.item.id);//#memberssearch-family_name_id is the id of hiddenInput. }")
Thanks
works
Thx, worked
$data = \common\models\User::find() ->select(['username as value', 'username as label', 'id as id']) ->asArray() ->all(); <?php $form = ActiveForm::begin(); ?> <?= AutoComplete::widget([ 'name' => 'Company', 'id' => 'ddd', 'value' => $model->user->username, 'clientOptions' => [ 'source' => $data, 'autoFill' => true, 'minLength' => '1', 'select' => new JsExpression("function( event, ui ) { $('#inoculation-id_user').val(ui.item.id); }")], 'options' => [ 'class' => 'form-control' ] ]); ?> <?= Html::activeHiddenInput($model, 'id_user') ?> <?php ActiveForm::end(); ?>
How to limit query, i've tried add ->limit(10) not working, my table have thousand rows contain same word make it slow.
Sorry for testing comment, i cannot delete it :)
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.