How to display images in CJuiAutoComplete without extenstions

I wanted to customize the CJuiAutoComplete, so that it displays a thumb image before the label like the one shown in the following image:

autocomplete thumb

Here is what you can do in a very simple way, in your model controller:

// In the access rules function
public function accessRules()
	return array(
	array('allow',  // allow all users to perform 'index' and 'view' actions
	'actions'=>array('index','view', 'getColorAjax'), // replace getColorAjax with your ajax function name

// Add your function, in my case it is called getColorAjax
// Place the query logic, make sure to set all the variables you need to display in your view
public function actionGetColorAjax(){
		$data = Yii::app()->db->createCommand()
		->where(array('like', 'color_id', "$request%"))

		$return_array = array();
		foreach($data as $sub) {
         // Set all of your view variables in this array
			$return_array[] = array(
         // This is the color name
         // This is the line containing the full path to the thumb image
			'img' => Yii::app()->request->baseUrl.Yii::app()->params["colorUploadUrl"].$sub['color_img']
		echo json_encode($return_array);

In your view file _In my case it was form:

$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
	'attribute' => 'color', // replace color with the attribute name
        'sourceUrl'=> '?r=colorCode/getColorAjax', // replace getColorAjax with your function name
		'placeholder'=>'color id',
// Here we override the default CJuiAutoComplete items display
// Feel free to add any styling that fits your needs
// N.B. #ColorCode_color is the yii generated id for this input field, use your browser inspector to find its id. Don't set the id of the CJuiAutoComplete to some random name, otherwise validation rules won't apply to this field
// I've placed the registration in the view file, you can place it wherever you want
// use "item." to access variables previously set in your query function _getColorAjax in my case_
Yii::app()->clientScript->registerScript ("Color#color-autocomplete", "
	$('#ColorCode_color').autocomplete().data( 'autocomplete' )._renderItem = function( ul, item ) {
		    return $('<li></li>')
		        .data('item.autocomplete', item)
		        .append('<a><img height=10px src=\"' + item.img + '\" alt=\"' + item.label+ '\" />' + '\t'+  item.label +'</a>')

Check the comments inside the code, that's it !


Your text to link here... Your text to link here...