greeting everyone. this is my first time using PHP and Yii.
i just implement a dependant dropdown base on http://www.yiiframework.com/wiki/24/creating-a-dependent-dropdown/#c4447 example.
the code below works fine, except i cannot save ‘category_id’ into database. the category_id return null.
first question : is that happen because i use "echo CHtml::dropDownList" instead of "echo $form->dropDownList"? can anyone guide me how to solve this problem?
// ==========
// _form.php
// ==========
<div class="form">
<?php
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
'id'=>'blog-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="help-block">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<?php
$topic=new Topic();
//TOPIC NOT NEED TO BE SAVED TO DATABASE
echo $form->labelEx($topic,'topic_id');
echo CHtml::dropDownList('topic_id','',Topic::getTopics(''),
array(
'prompt'=>'-- select topic --',
'ajax' =>
array(
'type'=>'POST',
'url'=>CController::createUrl('skn/Blog/GetCategoryByTopic'),
'update'=>'#category_id',
)
)
);
echo $form->error($topic,'topic_id');
//CATEGORY MUST BE SAVED, BUT RETURN NULL VALUE TO DATABASE
echo $form->labelEx($model,'category');
echo CHtml::dropDownList('category_id',$model, array(),array('empty' => '-- select topic --'));
echo $form->error($model,'category_id');
?>
<div class="form-actions">
<?php $this->widget('bootstrap.widgets.TbButton', array(
'buttonType'=>'submit',
'type'=>'primary',
'label'=>$model->isNewRecord ? 'Create' : 'Save',
)); ?>
</div>
<?php $this->endWidget(); ?>
</div>
// ==========
//BlogController.php
// ==========
public function actionGetCategoryByTopic()
{
$data=Category::model()->findAll('topic_id=:topic_id',
array(':topic_id'=>(int) $_POST['topic_id']));
$data=CHtml::listData($data,'category_id','category_name');
foreach($data as $value=>$name)
{
echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name),true);
}
}
second question : when i use "echo $form->dropDownList" for dependent dropdown, i get a PHP Warning like below,
but "echo CHtml::dropDownList" works fine. why is that happen ?
get_class() expects parameter 1 to be object, string given
C:\Apache\htdocs\framework\yii\framework\web\helpers\CHtml.php(2220)
2208 {
2209 $sub=substr($attribute,0,$pos+1);
2210 $attribute=substr($attribute,$pos+1);
2211 return get_class($model).$sub.'['.$attribute.']';
2212 }
2213 if(preg_match('/\](\w+\[.*)$/',$attribute,$matches))
2214 {
2215 $name=get_class($model).'['.str_replace(']','][',trim(strtr($attribute,array(']['=>']','['=>']')),']')).']';
2216 $attribute=$matches[1];
2217 return $name;
2218 }
2219 }
2220 return get_class($model).'['.$attribute.']'; //RED COLOUR HERE
2221 }
ok thats all. thank you. cheers