Versions
Look up a class, method, property or event

CJuiAutoComplete

Package zii.widgets.jui
Inheritance class CJuiAutoComplete » CJuiInputWidget » CJuiWidget » CWidget » CBaseController » CComponent
Since 1.1.2
Source Code framework/zii/widgets/jui/CJuiAutoComplete.php
CJuiAutoComplete displays an autocomplete field.

CJuiAutoComplete encapsulates the JUI autocomplete plugin.

To use this widget, you may insert the following code in a view:
$this->widget('zii.widgets.jui.CJuiAutoComplete',array(
    'name'=>'city',
    'source'=>array('ac1','ac2','ac3'),
    // additional javascript options for the autocomplete plugin
    'options'=>array(
        'minLength'=>'2',
    ),
    'htmlOptions'=>array(
        'style'=>'height:20px;',
    ),
));


By configuring the options property, you may specify the options that need to be passed to the JUI autocomplete plugin. Please refer to the JUI AutoComplete API documentation for possible options (name-value pairs) and JUI AutoComplete page for general description and demo.

By configuring the source property, you may specify where to search the autocomplete options for each item. If source is an array, the list is used for autocomplete. You may also configure sourceUrl to retrieve autocomplete items from an ajax response.

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
actionPrefix string the prefix to the IDs of the actions. CWidget
attribute string the attribute associated with this widget. CJuiInputWidget
controller CController Returns the controller that this widget belongs to. CWidget
cssFile mixed the theme CSS file name. CJuiWidget
htmlOptions array the HTML attributes that should be rendered in the HTML tag representing the JUI widget. CJuiWidget
id string Returns the ID of the widget or generates a new one if requested. CWidget
model CModel the data model associated with this widget. CJuiInputWidget
name string the input name. CJuiInputWidget
options array the initial JavaScript options that should be passed to the JUI plugin. CJuiWidget
owner CBaseController Returns the owner/creator of this widget. CWidget
scriptFile mixed the main JUI JavaScript file. CJuiWidget
scriptUrl string the root URL that contains all JUI JavaScript files. CJuiWidget
skin mixed the name of the skin to be used by this widget. CWidget
source mixed the entries that the autocomplete should choose from. CJuiAutoComplete
sourceUrl mixed the URL that will return JSON data as the autocomplete items. CJuiAutoComplete
theme string the JUI theme name. CJuiWidget
themeUrl string the root URL that contains all JUI theme folders. CJuiWidget
value string the input value. CJuiInputWidget
viewPath string Returns the directory containing the view files for this widget. CWidget

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. CComponent
__construct() Constructor. CWidget
__get() Returns a property value, an event handler list or a behavior based on its name. CComponent
__isset() Checks if a property value is null. CComponent
__set() Sets value of a component property. CComponent
__unset() Sets a component property to be null. CComponent
actions() Returns a list of actions that are used by this widget. CWidget
asa() Returns the named behavior object. CComponent
attachBehavior() Attaches a behavior to this component. CComponent
attachBehaviors() Attaches a list of behaviors to the component. CComponent
attachEventHandler() Attaches an event handler to an event. CComponent
beginCache() Begins fragment caching. CBaseController
beginClip() Begins recording a clip. CBaseController
beginContent() Begins the rendering of content that is to be decorated by the specified view. CBaseController
beginWidget() Creates a widget and executes it. CBaseController
canGetProperty() Determines whether a property can be read. CComponent
canSetProperty() Determines whether a property can be set. CComponent
createWidget() Creates a widget and initializes it. CBaseController
detachBehavior() Detaches a behavior from the component. CComponent
detachBehaviors() Detaches all behaviors from the component. CComponent
detachEventHandler() Detaches an existing event handler. CComponent
disableBehavior() Disables an attached behavior. CComponent
disableBehaviors() Disables all behaviors attached to this component. CComponent
enableBehavior() Enables an attached behavior. CComponent
enableBehaviors() Enables all behaviors attached to this component. CComponent
endCache() Ends fragment caching. CBaseController
endClip() Ends recording a clip. CBaseController
endContent() Ends the rendering of content. CBaseController
endWidget() Ends the execution of the named widget. CBaseController
evaluateExpression() Evaluates a PHP expression or callback under the context of this component. CComponent
getController() Returns the controller that this widget belongs to. CWidget
getEventHandlers() Returns the list of attached event handlers for an event. CComponent
getId() Returns the ID of the widget or generates a new one if requested. CWidget
getOwner() Returns the owner/creator of this widget. CWidget
getViewFile() Looks for the view script file according to the view name. CWidget
getViewPath() Returns the directory containing the view files for this widget. CWidget
hasEvent() Determines whether an event is defined. CComponent
hasEventHandler() Checks whether the named event has attached handlers. CComponent
hasProperty() Determines whether a property is defined. CComponent
init() Initializes the widget. CJuiWidget
raiseEvent() Raises an event. CComponent
render() Renders a view. CWidget
renderFile() Renders a view file. CBaseController
renderInternal() Renders a view file. CBaseController
run() Run this widget. CJuiAutoComplete
setId() Sets the ID of the widget. CWidget
widget() Creates a widget and executes it. CBaseController

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
hasModel() Determines whether this widget is associated with a data model. CJuiInputWidget
registerCoreScripts() Registers the core script files. CJuiWidget
registerScriptFile() Registers a JavaScript file under scriptUrl. CJuiWidget
resolveNameID() Resolves name and ID of the input. Source property of the name and/or source property of the attribute CJuiInputWidget
resolvePackagePath() Determine the JUI package installation path. CJuiWidget

Property Details

source property
public mixed $source;

the entries that the autocomplete should choose from. This can be

  • an Array with local data
  • a String, specifying a URL that returns JSON data as the entries.
  • a javascript callback. Please make sure you wrap the callback with CJavaScriptExpression in this case.

sourceUrl property
public mixed $sourceUrl;

the URL that will return JSON data as the autocomplete items. CHtml::normalizeUrl() will be applied to this property to convert the property into a proper URL. When this property is set, the source property will be ignored.

Method Details

run() method
public void run()
Source Code: framework/zii/widgets/jui/CJuiAutoComplete.php#73 (show)
public function run()
{
    list(
$name,$id)=$this->resolveNameID();

    if(isset(
$this->htmlOptions['id']))
        
$id=$this->htmlOptions['id'];
    else
        
$this->htmlOptions['id']=$id;
    if(isset(
$this->htmlOptions['name']))
        
$name=$this->htmlOptions['name'];

    if(
$this->hasModel())
        echo 
CHtml::activeTextField($this->model,$this->attribute,$this->htmlOptions);
    else
        echo 
CHtml::textField($name,$this->value,$this->htmlOptions);

    if(
$this->sourceUrl!==null)
        
$this->options['source']=CHtml::normalizeUrl($this->sourceUrl);
    else
        
$this->options['source']=$this->source;

    
$options=CJavaScript::encode($this->options);
    
Yii::app()->getClientScript()->registerScript(__CLASS__.'#'.$id,"jQuery('#{$id}').autocomplete($options);");
}

Run this widget. This method registers necessary javascript and renders the needed HTML code.

Total 6 comments

#17154 report it
marcovtwout at 2014/05/08 03:51am
Passing key-value array to source

You can convert your typical key/value array into an object jQuery can use. Use this when you want to show the value and store the key:

<?php $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
    'model' => $form,
    'attribute' => 'code',
    // $codeList contains key=>label pairs, typically from CHtml::listData
    'source' => array_map(function($key, $value) {
        return array('label' => $value, 'value' => $key);
    }, array_keys($codeList), $codeList),
)); ?>
#9849 report it
szfjozsef at 2012/09/15 03:01am
Automatically submit the form

Upon picking something from the dropdown list, by default the form isn't submitted. When you have a search input for example, it's annoying to pick something and then explicitly press the 'Search' button which will submit the form. Include

'submit' => '',

into htmlOptions so clicking an item from the dropdown list will submit the form.

#9404 report it
xNicox at 2012/08/08 11:14pm
How to use more data in suggest list box.

Hi, I figured out how to show more data in the suggest list box.

Jquery UI Autocomplete widget has a demo in their site But it uses ".data" function. So I need to add this function to the view.

$js = "jQuery('#alumno')";
        $js .= ".data( 'autocomplete' )._renderItem = function( ul, item ) {
            return $( '<li></li>' )
                .data( 'item.autocomplete', item )
                .append( '<a>' + item.label + '<br><b>Doc:</b>' + item.documento + ' <b>Grado:</b>' + item.grado + '</a>' )
                .appendTo( ul );
        };";
 
        $cs = Yii::app()->getClientScript();
        $cs->registerScript(__CLASS__.'#CtaCte_alumno_', $js);

The tag "alumno" is related to the CJuiAutomplete "name" atribute. In the append function I think you could add anything, and is treted like HTML. I hope this help somebody.

Best Regards

#8376 report it
Ben at 2012/05/29 05:26pm
Highlight search hits

Most of the times I use the widget, I also want to highlight the search term within each result. And every time I have to google how to do it. So here it is:

$class  = get_class( $model );
$attrib = 'fooBar';
 
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
  'model'       => $model,
  'attribute'   => $attrib,
));
 
Yii::app()->clientScript->registerScript('unique.script.identifier', "
  $('#{$class}_{$attrib}').data('autocomplete')._renderItem = function( ul, item ) {
    var re = new RegExp( '(' + $.ui.autocomplete.escapeRegex(this.term) + ')', 'gi' );
    var highlightedResult = item.label.replace( re, '<b>$1</b>' );
    return $( '<li></li>' )
      .data( 'item.autocomplete', item )
      .append( '<a>' + highlightedResult + '</a>' )
      .appendTo( ul );
  };
");
#7599 report it
pligor at 2012/04/02 11:21am
conflict

Let's say that you have multiple forms inside the same view. And let's say that all these forms belong to the same model. Then all the rendered ids of these divs are the same. The jquery inside run() method will search all of the page and apply the autocomplete to the first element. Therefore all the rest of the input textboxes will not have autocomplete!

My current solution is to use methods of UUID like

sha1(microtime(true)

to set the id. Of course this has its drawbacks in case you are depended on the convention "ClassName_attributeName" for the id

#6852 report it
marcovtwout at 2012/02/09 06:40am
Passing array to source

If you want to pass an array to the source, you can only pass values:

<?php $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
    'model' => $form,
    'attribute' => 'username',
    // $userList contains id=>username pairs
    'source' => array_values($userList), // only use values, otherwise its converted to js Object and that doesn't work
)); ?>

Leave a comment

Please to leave your comment.