Typeahead Bootstrap + Ajax

Hello guys,

i have searched the i-net for a solution to change the source of the typeahed via ajax and thus i didnt find a solution i coded it myself and would like to share with others, if somoone needs:

  1. View:



		<div class="control-group ">

			<label class="control-label" for="Customer_companyGroup"><?php echo $model->getAttributeLabel('companyGroup_id'); ?>

			</label>

			<div class="controls">

				<?php $this->widget('bootstrap.widgets.TbTypeahead', array(

						'name'=>'Customer[companyGroup]',

						'id'=>'Customer_companyGroup',

						'value'=>$model->companyGroup->title,

						'options'=>array(

								'source'=>array(),

								'items'=>4,

								'matcher'=>"js:function(item) {

								return ~item.toLowerCase().indexOf(this.query.toLowerCase());

}",

						),

)); ?>

			</div>

		</div>


<script type="text/javascript">

	var token = "<?php echo Yii::app()->request->csrfToken;?>";


	$('#Customer_companyGroup').keydown(function(key) {

		console.log($('#Customer_companyGroup').val().length);

		if($('#Customer_companyGroup').val().length > 2){

			$.post('/crm/customer/findCompanyGroups', { name: $('#Customer_companyGroup').val(),YII_CSRF_TOKEN:token }, function (data) {

				data = JSON.parse(data);

				found = [];

				$.each(data, function (i, group) {

					found.push(group.title);

			    });

				$('#Customer_companyGroup').data('typeahead').source = found;

	        });

		}

	});

</script>



  1. Controller:



	public function actionFindCompanyGroups() {

		if (Yii::app() -> request -> isAjaxRequest && isset($_POST['name'])) {

			$sql = 'SELECT * FROM table WHERE title LIKE "%'.$_POST['name'].'%"';

			$arr = Yii::app()->db->createCommand($sql)->queryAll();

			echo json_encode($arr);

		}

	}



Have a nice day!

dont work


$('#Customer_companyGroup').data('typeahead').source = found;


Uncaught TypeError: Cannot set property 'source' of undefined 

You should change "#Customer_companyGroup" -> to your typeahed ID

Hi, thank you for your sharing. I find this way to do this:

Create a file FindGroupAction.php in controllers folder.

Put this code inside the file:




<?php

class FindGroupAction extends CAction

{

	public function run() {

        if (Yii::app()->request->isAjaxRequest && isset($_POST['group'])) {

            $group = $_POST['group'];

            $listGroups = Cap::model()->findAll(

            	'group LIKE :group',

            	array(':group' => '%'.$group.'%'));

            $groups = array();

			foreach($listGroups as $group)

			{

    			$groups[] = $group->title;

			}

            echo CJSON::encode($groups);

        }

    }

}



After i add an Action in MyController.php




public function actions()

	{

		return array(

			'findgroup' => 'application.controllers.FindGroupAction',

		);

	}



End edit the js in the view:




......

$.each(data, function (i, group) {

    found.push(group);

});

......



Have a nice day