CJuiAutoComplete HowTo

There is very good example of CJuiAutocomplete with multiple JSON variable at www.eha.ee/labs/yiiplay/index.php/en/site/widget?view=autocomplete . There is no need to add ‘methodChain’. default CJuiAutocomplete has option to support multiple variables. Remember your JSON return should be in this format:


[{"key1":"value1", "key2":"value2"},{"key3":"value3","key4":"value4"}]

Thanks for the discussion

[color="#FF0000"]<?php echo $form->hiddenField($model,‘user_id’); ?>[/color]

in _form.php i did following:




//this line is important.

<?php echo $form->hiddenField($model,'user_id'); ?>


$this->widget('zii.widgets.jui.CJuiAutoComplete', array(

    'name'=>'username',

    

    'source'=>$this->createUrl('jui/autocompleteTest'),

    // additional javascript options for the autocomplete plugin

    'options'=>array(

        'showAnim'=>'fold',

        'select'=>"js:function(event, ui) {

                                          $('#user_id').val(ui.item.id); 

                                        }" //note #user_id

    ),

    'cssFile'=>false,

));



in JuiController.php i did following in actionAutocompleteTest():




$arr = array();

foreach($models as $model) {

    $arr[] = array(

        'label'=>$model->some_attr,  // label for dropdown list          

        'value'=>$model->some_attr,  // value for input field          

        'id'=>$model->id,            // return value from autocomplete

        );      

}

echo CJSON::encode($arr);



And you can do without a controller




$this->widget(

    'zii.widgets.jui.CJuiAutoComplete',

    array(

        'model' => $model,

        'attribute' => '{attribute}',

        'source' => array_keys(CHtml::listData($model->findAll(array('select' => '{attribute}')), '{attribute}', '{attribute}')),

        'options' => array(

            'minLength' => '2',

        )       

    )

);




Is there a way to submit to the same model/action with query params ?

I need to select a name, but submit an Id…

It’s so difficult

Answer is here. Look at last example and browse at code.

www.eha.ee/labs/yiiplay/index.php/en/site/widget?view=autocomplete

I had use this in my project and it work.

I tried with the previous example but i’m getting the values and it is coming up with id in alertbox as well…when i checked the network inspector in chrome…values are coming up fine. but the values are not being visible.

you can see my full code in here:


        <div class="row">

        <?php echo $form->labelEx($typeModel,'benefit_type'); ?>

        <?php

         

         $this->widget('zii.widgets.jui.CJuiAutoComplete', array(

        		'model'=>$model,

        		'attribute'=>'name',

        		'source'=>$this->createUrl('benefit/benefit_type_list'),

        		// additional javascript options for the autocomplete plugin

        		'options'=>array(

        				'showAnim'=>'fold',

        				'select'=>"js:function(event, ui) {

                                          $('#User_user_id').val(ui.item.id);

                                        }"

        		),

        		'cssFile'=>false,

        ));

    ?>

        

        <?php echo $form->error($typeModel,'benefit_type'); ?>

    </div>



I tried both the ways but output is same values are not being displayed…




    <div class="row">

        <?php echo $form->labelEx($typeModel,'benefit_type'); ?>

        <?php

    $this->widget('zii.widgets.jui.CJuiAutoComplete', array(

    'attribute'=>'name',

    'model'=>$typeModel,

    'sourceUrl'=>array('benefit/benefit_type_list'),

    'value'=>'Please select',

    'name'=>'name',

    'id'=>'id',

    'options'=>array(

'showAnim'=>'fold',

        'minLength'=>'0',

         'select'=>"js:function(event, ui) {

     alert(ui.item.id);

                                        // $('#BenefitType_benefit_type_id').val(ui.item.id);

                                        }",

    ),

'cssFile'=>false,


    'htmlOptions'=>array(

'id'=>'id',

    'size'=>25,

    'maxlength'=>25,

    ),

    )); ?>

      

        <?php echo $form->error($typeModel,'benefit_type'); ?>

    </div>

can anyone pls help me

Thanks in advance

This simple CjuiCode is fetching the autocomplete for the text field…but can anyone pls tell me how to capture this value in controller???

thanks in advance…


<div class="row">

        

        <?php echo $form->hiddenField($typeModel,'id'); ?>

        <?php

        

        $this->widget('zii.widgets.jui.CJuiAutoComplete',

        		array('model' => $typeModel,

        			'attribute' => 'name',

        			'source' => array_keys(CHtml::listData($typeModel->findAll(array('select' => 'name')), 'name', 'id')),

        			'options' => array(

        			'minLength' => '1',

        		       )

        		    ));

      

        

    ?>

  


    </div>

Im trying something like this but its not coming up in controller


var_dump($_POST['TypeModel']['id']);die;

Thanks alot for your simply superb cjuiautocomplete code :). Its working for me now :)

View Form.php:




  <?php echo $form->labelEx($model,'name'); ?>

            <?php $this->widget('zii.widgets.jui.CJuiAutoComplete', array(                    

            'name'=>'name',

            // 'type'=>'POST',

            'source'=>$this->createUrl('/RamDbf/getNameIDs'),// <- path to controller which returns dynamic data

            // additional javascript options for the autocomplete plugin

            'options'=>array(

            'minLength'=>'1', // min chars to start search

            'select'=>'js:function(event, ui) { 

            $("#DiagonisticEntryForm_name").val(ui.item.id);

            }'

            ),

            'htmlOptions'=>array(

            'id'=>'getNameIDs',

            'rel'=>'val',

            'style' => 'width: 315px'

            ),

            ));

            ?>

            <?php echo $form->error($model,'name'); ?>



controller:




public function actiongetNameIDs(){

    

                $list           = array();

                $term           = isset($_REQUEST['term']) ? trim($_REQUEST['term']) : "";

                $term           = addcslashes($term, '%_'); // escape LIKE's special characters


                $criteria = new CDbCriteria();

                $params   = array();

                if(!empty($term)){

                $criteria->condition =   "name LIKE :term" ;

                $params[':term'] = "%$term%";

                }


                $criteria->params = $params;

                $criteria->offset = 0;

                $criteria->limit  = 50;

                $criteria->order  = "id ASC";

                $referers         = RamDbf::model()->findAll($criteria);


                foreach($referers as $test){

                $item             = array();

                $item['id']       = $test->id;

                $item['value']    = $test->name;


                $list[] = $item;

                }


                echo json_encode($list);

                Yii::app()->end();

}




This a great code! Thanks for this!

Hi, there is my solution I’ve made thank’s to your replies. I improved it to have a nice combobox with kind of “must match” function and scrollable results. I only show the view form part as the controller one does not change a lot from the examples above.


    <div class="row">

        <?php echo CHtml::label('User', 'uidlabel'); ?>

        <style>

        .ui-autocomplete {

          max-height: 280px;

          overflow-y: auto;

          /* prevent horizontal scrollbar */

          overflow-x: hidden;

        }

        /* IE 6 doesn't support max-height

         * we use height instead, but this forces the menu to always be this tall

         */

        * html .ui-autocomplete {

          height: 280px;

        }

        #alertMatch

        {

        display:none;

        }

        </style>

        <?php

        $currentCompletename = $model->uid->cn;

                  

        $this->widget('zii.widgets.jui.CJuiAutoComplete',array(

            'name'=>'combobox',

            'source' => $this->createUrl('/specialUser/autoCompleteLookup'),

            'value' => $currentCompletename,

            // additional javascript options for the autocomplete plugin

            'options'=>array(

                'minLength'=>'3',

                'delay' => 500,

                'select'=>'js:function(event, ui) {'

                    . '$("#SpecialUser_uid").val(ui.item.id);'

                      // Alert removal

                    . '$("#alertMatch").slideUp(500, function() {'

                        . '$("#alertMatch").html("")'

                    . '});'

                . '}',

                'change'=>'js:function(event, ui) {'

                      // Value does not match or field is empty

                    . 'if (!ui.item || $(this).val()=="") {'

                          // Alert only whith case value does not match

                        . 'if ($(this).val()!="") {'

                            . '$("#alertMatch").html("<div class=' . "'" . 'error' . "'" . '><b>Unknown User. Choose a matching value in the list</b></div>");'

                            . '$("#alertMatch").slideDown(250);'

                        . '};'

                          // In both cases sets an empty string in the hidden field 

                          // (id SpecialUser_uid as SpecialUser is the name of the model and uid the attribute)

                        . '$("#SpecialUser_uid").val("");'

                        . '$(this).val("");'

                    . '}'

                . '}',

                'showAnim' => 'fold'

            ),

            'htmlOptions'=>array(

                'style' => 'width: 331px',

                'id'=>'getNameIDs',

                'rel'=>'val'

            ),

        ));

        

        echo '<div id="alertMatch"></div>';      

        echo CHtml::activeHiddenField($model,'uid');

        echo CHtml::error($model, 'uid'); ?>

    </div>

Im using the plugin and it works fine! But I want to retrieve the ID of the selected item and I get the NAME. How can I get the id? The way I use to retrieve the field is Yii::app()->request->getPost(‘field_id_save’, ‘’);