所以我有一个CListView,我可以使用我在sortableAttributes中设置的属性进行排序,当它只是ASC和DESC排序时,这很好。但我也想按类别对CListView进行排序。在我的模型中,我有一个类别,范围从 0-8。我做了一个显示类别的下拉选择。
我想做的是在选择下拉列表中的选项时更新我的 CListView,我可以为此编写自己的 jQuery 代码,但我猜有一些聪明的 yii 方法可以做到这一点。
谢谢
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$model->search(),
'sortableAttributes'=>array('views','create_time','release_time'),
'id'=>'#videos',
'itemView'=>$view,
'pager'=>array('cssFile'=>'/css/pager.css'),
)); ?>
经过一番辛劳
:您必须做两件事。首先,我们需要来自服务器的修改数据,为此,您可以修改模型的搜索函数,因为这是为 CListView 提供数据提供程序的函数。
因此,在模型的search()
函数中,您可以添加一个if
条件来修改数据提供程序的$criteria
,例如:
public function search() {
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
// added the following if condition to modify the criteria to include only videos of a certain category
if (isset($_GET['category']))
$criteria->compare('category',$_GET['category'],true);// my category is string, hence the third attribute
else
$criteria->compare('category',$this->category,true);// we need the else part, coz the search function is used for actual searching also, for instance in gridview filters/search
$criteria->compare('id',$this->id);
// your other attributes follow
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
注意:我不确定在比较之前是否绝对有必要对 $_GET['category'] 进行消毒。
其次,我们需要更新CListView,我们可以将其功能用于 $.fn.yiiListView.update
。所以例如:
<div id="categoryupdating">
<?php
echo CHtml::dropDownList('dropit', '',
array('1'=>'Cateogry1','2'=>'Category2','3'=>'Category3','4'=>'Category4'),
array('onchange'=>"$.fn.yiiListView.update('videos', {url: '".Yii::app()->createUrl('controller/action')."?category='+$('#dropit option:selected').val()})"));
?>
</div>
当然,在这里,您应该使用诸如 CHtml::listData
之类的函数动态填充下拉列表的数据,并且控制器/操作应该是 CListView 的控制器/操作。
查看 jquery.yiilistview.js 文件以了解有关 yii listview widget 的 JavaScript 函数的更多信息。
注意:$.fn.yiiListView.update 将列表视图的id
和要调用更新的url
作为参数。
编辑:还添加了else
条件,因为搜索功能用于网格视图和其他地方的实际搜索。
为了将来参考,这就是我最终这样做的方式。
Yii::app()->clientScript->registerScript('category', "
$('#category').change(function(){
$.fn.yiiListView.update('videos', {
data: $(this).serialize()
});
return false;
});
");
重要的部分是 dropDownList 的 htmlOptions 中的 id,因为您不能使用 "Video[category]" 作为 $.fn.yiiListView.update 函数的 id。但是需要它作为选择的名称,以便能够使用已经存在的搜索功能。
<?php echo CHtml::dropDownList(
'Video[category]',
0,
Lookup::items('VideoCategory'),
array('id' => 'category')
); ?>