Hello! how can one use the Typeahead (bootstrap.widgets.TbTypeahead) OR CJuiAutoComplete to have autocomplete feature on related models (foreign key one-to-many relation)?
This is a very common scenario.
For example, when you have the following models and fields::
User.id_city
City.id
City.name
User.id_city is a foreign key to City.id
I’d like to do something similar to the following:
$this->widget('bootstrap.widgets.TbTypeahead', array(
'model'=>$model, // instance of model 'User'
'attribute'=>'id_city', // foreign key field
'options'=>array(
'source'=>City::model()->findAll(),
'valueAttribute'=>'id', // city.id
'displayAttribute'=>'name', // city.name
'items'=>4,
'matcher'=>"js:function(item) {return ~item.toLowerCase().indexOf(this.query.toLowerCase());}",
)
)
));
In other words, similar to how you can use the traditional drop-down list:
<?php echo $form->dropDownList($model, 'id_city', CHtml::listData(City::model()->findAll(), 'id', 'name')); ?>
…but with autocomplete feature.
How can this be done? Thank you.
UPDATE:
After reading a lot of forum posts, I can see that Typeahead and CJuiAutoComplete were not designed to work with "value and display" attributes of related models so you can use the required value/id of a selected display/name to submit for model creation/update.
Typeahead and CJuiAutoComplete seem to behave like “simple” autocomplete textboxes and I couldn’t see an easy way to implement the value/display attributes behavior.
Fortunately for me, I found the select2 extension and it was as simple as copying the extension folder and using the following in a view:
<?php $this->widget('ext.select2.ESelect2',array(
'model'=>$model,
'attribute'=>'id_city',
'data'=>CHtml::listData(City::model()->findAll(), 'id', 'nombre'),
)); ?>
Simple code to implement, works fine and looks nice.
Just wanted to share what I used as a solution.