Auto Complete Text Box

hiii…

I need a auto complete text box with drop down list like This Example. Actualy the 3 rd example in this link I need .

For doing this

1st : I add a page named XSuggestAction.php in extensions/actions directory add put the following code:




<?php

class XSuggestAction extends CAction

{

/**

* @var string name of the model class.

*/

public $modelName;

/**

* @var string name of the method of model class that returns data.

*/

public $methodName;

/**

* @var integer maximum number of rows to be returned

*/

public $limit=20;

/**

* Suggests models based on the current user input.

*/

public function run()

{

if(isset($_GET['term'])&&($keyword=trim($_GET['term']))!=='')

{

$suggest=$this->getModel()->{$this->methodName}($keyword,$this->limit,$_GET);

echo CJSON::encode($suggest);

}

}

/**

* @return CActiveRecord

*/

protected function getModel()

{

return CActiveRecord::model($this->modelName);

}

}

?>



[b]

2nd :[/b] Then I add following code in My Controller page :





public function actions()

    {

        return array(

             'suggestProduct'=>array(

             'class'=>'ext.actions.XSuggestAction',

             'modelName'=>'Product',

             'methodName'=>'suggest',

        ));

	}



3rd : Then I add following code in my Model page :




    public function suggest($keyword,$limit=20)

   {

        $models=$this->findAll(array(

           'condition'=>'product_name LIKE :keyword',

           'order'=>'product name',

           'limit'=>$limit,

           'params'=>array(':keyword'=>"%$keyword%")

        ));

       $suggest=array();

           foreach($models as $model) {

             $suggest[] = array(

               

                'product_sale_rate'=>$model->product_sale_rate, // return values from autocomplete

        );

    }

return $suggest;

}



4th : I add the following code in my view page which is _form.php




<?php

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

    //'model'=>$model,

    //'attribute'=>'name',

    'id'=>'Product_list',

    'name'=>'product_name',

    'source'=>$this->createUrl('request/suggestProduct'),

    'options'=>array(

        'delay'=>300,

        'minLength'=>1,

        'showAnim'=>'fold',

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

            $('#sale_rate').val(ui.item.product_sale_rate);

            

        }"

    ),

    'htmlOptions'=>array(

        'size'=>'40'

    ),

));


?>






and Add the following code in same page :




	<div class="row" id="sale_rate">

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

		<?php echo $form->textField($model,'product_sale_rate'); ?>

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

	</div>



Now problem is nothing happens when I write some thing in the text field . I want a drop down list of my product which i get from Product model and the price of that particular product shows in the text field whose id is sale_rate .

Plz help me . I Attach my codes With this post . thnx .

Hi.

First of all, you haven’t a controller called “request”. Then, it’s impossible it works.

Your CJuiAutocomplete must be:




<?php

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

    //'model'=>$model,

    //'attribute'=>'name',

    'id'=>'Product_list',

    'name'=>'product_name',

    'source'=>$this->createUrl('SalesReport/suggestProduct'),

    'options'=>array(

        'delay'=>300,

        'minLength'=>1,

        'showAnim'=>'fold',

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

            $('#sale_rate').val(ui.item.product_sale_rate);

            

        }"

    ),

    'htmlOptions'=>array(

        'size'=>'40'

    ),

));


?>



Try this and then you comment me.

Thnk u for ur reply… But itz not working … I tried this after ur suggestion…

Also you need add your action to the controller rules.




public function accessRules()

{

     return array(

            array('allow',

                 'actions'=>array('suggestProduct',...

...

...



Plz suggest me if there is any other way do this auto complete … :rolleyes:

No… not working




array('allow',

                 'actions'=>array('suggestProduct'




I add this …

In your SalesReport controller you have this:




public function actions()

    {

        return array(

             'suggestProduct'=>array(

             'class'=>'ext.actions.XSuggestAction',

             'modelName'=>'Product',

             'methodName'=>'suggest',

        ));

	}



But you have the "suggest" method into "SalesReport" model, not in"Product" model.

You have to read the example again because you have many faults. If you follow the example it will work.

ok thnx … I will try again …

Help Me guzz…

:blink:

Help me plzzz.

try this out

https://gist.github.com/alirz23/b4c9b0ccebe2543dae18

hiii…

This is my view part :




	<div class="row">

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

		<?php $products = CHtml::listData(product::model()->findAll(),'product_sale_rate','product_name');


            $options = array(

                'empty' => '--Select a Product--',

                'ajax' => array('type'=>'POST'

                                , 'url'=>CController::createUrl('SalesReport/GetPrice')

                                , 'update'=>'#price_id'  //selector to update

                )

            );

        

        echo CHtml::dropDownList('product_name', '', $products, $options);


		 ?>

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

	</div>


	<div class="row" id="price_id">

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

		<?php 

            echo CHtml::textField( 'temp_id') ;

        ?>

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

	</div>



And This is my controller part :




	  public function actionGetPrice()

        {

            //Model::model()->price();

            //$product_id = (int)$_POST['product_name'];

			//$product_price= Yii::app()->db->createCommand('select product_price from product where product_id=112')->query();

          

			echo CHtml::tag('input', array( 'type'=>'text' , 'value' => (int)$_POST['product_name']));


			

        }



Itz working…

But I want to add some query in controller. How can I do that . For Example :




	  public function actionGetPrice()

        {

            

            $product_id = (int)$_POST['product_name'];

	    $product_price= Yii::app()->db->createCommand('select product_price from product where product_id=$product_id')->query();

          

			echo CHtml::tag('input', array( 'type'=>'text' , 'value' => $product_price));


			

        }



But itz not working… Help me plz…

Good mornig, Debasis.

Regarding your private message, what do you want to do?

Productos should be a model, not a list data, for example. And data should be filled in the controller, not in the view.

Explain a little better, please.

MY VIEW PART CODE :




// CODE FOR DROP DOWN MENU

<div class="row">

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

		<?php 

		

		$products = CHtml::listData(product::model()->findAll(),'product_id','product_name');


            $options = array(

                'empty' => '--Select a Product--',

                'ajax' => array('type'=>'POST'

                                , 'url'=>CController::createUrl('SalesReport/GetPrice')

                                , 'update'=>'#price_id'  //selector to update

                )

            );

        

           echo CHtml::dropDownList('product_name', '', $products, $options);

             //echo $form->dropDownList($model,'product_name',CHtml::listData(product::model()->findAll(),'product_id','product_name'), $options);

		 ?>

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

	</div>

//CODE FOR PRODUCT SALE RATE TEXT FIELD

	<div class="row" >

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

		<div  id="price_id">

		<?php echo $form->textField(product::model(),'product_sale_rate',array('value'=>'0')); ?>

		</div>

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

	</div>



WHEN SOME ONE SELECT SOME VALUE FROM DROP DOWN THEN ITS GO TO THE CONTROLLER TO FIND THE CORRESPONDING SALE RATE AND ECHO A TEXT FIELD WITH A VALUE .

THIS IS THE CODE OF CONTROLLER :




 public function actionGetPrice()

        {

            //Model::model()->price();

         $product_id = (int)$_POST['product_name'];

		 //echo $product_id;

		

         $data = Yii::app()->db->createCommand()->

          select('product_sale_rate')->

          from('product')->

          where(array('like', 'product_id',$product_id))->

          queryAll();


          //var_dump($data);

		  $a= array_shift($data);

		  $result= array_shift($a);

		  

         

		 echo( 

		       CHtml::tag('input', array('type'=>'text' , 'value' => $result))

			 );


			

        }



NOW THE PROB IS WHEN I TRY TO SUBMIT THE FORM THEN IT SAID THAT THE FIELDS ARE EMPTY .

I ATTACH SOME SCREEN SHORT FOR BETTER UNDERSTANDING …

Everything works correctly except the submit, is it?

You can do this by two ways:

1- With models:

When you save data into database from action controller, normally it does this by models.

Then, in your form you should have related HTML elements with the model. But if you check your code, you can see it isn’t so.

You should have somethong like this:

view:




echo CHtml::activeDropdownList(

     $model,

     'product_name',

     $products,

     $options

);


echo CHtml::activeTextField(

     $model,

     'product_sale_rate'

);



In your controller action getPrice:




...

echo CHtml::activeTextField(

      product::model(),

     'product_sale_rate'

);

...



2- Without models:

view:




echo CHtml::dropdownList(

     'nameOne',

...


echo CHtml::textField(

     'nameTwo',

...



In your controller action getPrice:




...

echo CHtml::tag('input', array('id'=>'nameTwo', 'type'=>'text' , 'value' => $result));


...



Then in your action create:




$model->product_name = $_POST['nameOne'];

$model->product_sale_rate = $_POST['nameTwo'];



I’m not have tested the above code so that maybe I have some erros in it but you get the idea.

Greetings.

You can easily do with CJuiAutoComplete, visit this links and get idea.

links -

http://www.yiiframework.com/doc/api/1.1/CJuiAutoComplete

http://www.yiiframework.com/wiki/162/a-simple-action-for-cjuiautocomplete/

http://www.yiiframework.com/extension/multicomplete/