After spending a couple hours at doing some test, finally i end up with this solution. I’m not sure if my code good enough considering as best practice, but it works.
The autocomplete TextField:
<?php echo $form->hiddenField($model,'customer_id',array()); ?>
<?php $this->widget('zii.widgets.jui.CJuiAutoComplete',
array(
'model'=>$model,
'attribute'=>'corp_code',
'source'=>$this->createUrl('customer/getcustomer'),
'options'=>
array(
'minLength'=>3,
'showAnim'=>'fold',
'select'=>"js:function(event, ui) {
$('#SupportRequest_customer_id').val(ui.item.id);
getPackages(ui.item.id);
}"
),
'cssFile'=>false,
));
?>
My getcostumer controller action.
public function actionGetCustomer()
{
if (isset($_GET['term']))
{
$criteria=new CDbCriteria(array(
'alias'=>'customer',
'condition'=>"customer.corp_code like '" . $_GET['term'] . "%'",
));
$dataProvider=new CActiveDataProvider('Customer', array(
'criteria'=>$criteria,
'pagination' => false,
));
$customers = $dataProvider->getData();
$return_array = array();
foreach ($customers as $customer)
{
$return_array[] = array(
'label' => $customer->corp_code . ' - ' . $customer->corp_name,
'value' => $customer->corp_code,
'id' => $customer->id,
);
}
echo CJSON::encode($return_array);
}
}
Register Javascript code in view.
<?php Yii::app()->clientScript->registerScript("methodchain","
function getPackages(cid){
$.ajax({
url: '". $this->createUrl('dynamicpackage')."',
data: 'cid='+cid,
success: function(packages) {
$('#".CHtml::activeId($model, 'package_id')."').html(packages);
}
});
}
$(document).ready(function() {
getPackages($('#SupportRequest_customer_id').val());
});
",CClientScript::POS_END);
?>
Controller called by Ajax for populating dropdownlist:
public function actionDynamicPackage()
{
$data=Package::model()->findAll('customer_id=:customer_id',
array(':customer_id'=>(int)$_GET['cid']));
$data=CHtml::listData($data,'id','sp_number');
foreach($data as $value=>$sp_number)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($sp_number),true);
}
}
An empty dropdownlist to be bind with the data from ajax:
<?php echo $form->dropDownList($model,'package_id',array(), array('empty'=>'- Select -')); ?>
That’s it! Happy coding!!