How to display images in CJuiAutoComplete without extenstions

You are viewing revision #3 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#4) »

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

For me I needed to display a color thumb "color_img" before the color name "color_desc_e". Here is what you can do: 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 _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 inline the code, that's it !

0 0
Viewed: 10 003 times
Version: Unknown (update)
Category: Tutorials
Written by: Asmaa
Last updated by: samdark
Created on: Oct 9, 2014
Last updated: 2 years ago
Update Article


View all history

Related Articles