Chtml中三级联动实例(Yii框架)


控制器中根据父类Id,查找到所有子类,并以listOptions的形式返回到页面:


public function actionGetChildByParent($parent_id)
{
    $parentId = $parent_id;
    if (!$parentId) {
        return array();
    }
    $models = TicketCategory::model()->findAllByAttributes(array('parent_id'=>$parentId));
    $listData = CHtml::listData($models, 'id', 'show_title');
    $htmlOptions = array('empty'=>'请选择');
    $result = Chtml::listOptions('', $listData, $htmlOptions);
    echo $result;
}



视图中,用htmlOptions中的一个属性ajax完成ajax请求及处理:

(由于updata参数只能替换一个节点,所以这里把第一个select的ajax成功函数用success来处理)


<td><?php echo $form->labelEx($model,'cat_1_id'); ?></td>
<td>
    <?php echo $form->dropDownList($model, 'cat_1_id', TicketCategory::getCategoryArr(0), array("id"=>"Ticket_cat_1_id",'ajax'=>array(
        'type'=>'get',
        'url'=>Yii::app()->createUrl('ticket/getChildByParent'),
        'success'=>'function(html){$("#Ticket_cat_2_id").html(html).change();}',
        'data'=>array('parent_id'=>'js:this.value'),
    ))); ?>
</td>
<td width="120"><?php echo $form->error($model,'cat_1_id'); ?></td>
<td><?php echo $form->labelEx($model, 'cat_2_id'); ?></td>
<td>
        <?php echo $form->dropDownList($model, 'cat_2_id', TicketCategory::getCategoryArr($model->cat_1_id), array('onchange'=>'$("this").change()',"id"=>"Ticket_cat_2_id",'ajax'=>array(
            'type'=>'get',
            'url'=>Yii::app()->createUrl('ticket/getChildByParent'),
            'update'=>'#Ticket_cat_3_id',
            'data'=>array('parent_id'=>'js:$("#Ticket_cat_2_id").val()')
        ))); ?>
        <?php echo  CHtml::hiddenField('cat2Url',$cat2Url, array('id'=>'cat2Url')); ?>
</td>
<td width="120"><?php echo $form->error($model,'cat_2_id'); ?></td>
<td><?php echo $form->labelEx($model,'cat_3_id'); ?></td>
<td>
    <?php echo $form->dropDownList($model, 'cat_3_id', TicketCategory::getCategoryArr($model->cat_2_id), array("id"=>"Ticket_cat_3_id")); ?>
</td>
<td width="120"><?php echo $form->error($model,'cat_3_id'); ?></td>


你可能感兴趣的:(三级联动,dropdownlist,listData,listOptions,CHtml)