Using CListView to display items next to each other (in columns)

8 followers

This wiki article has not been tagged with a corresponding Yii version yet.
Help us improve the wiki by updating the version information.

When using CListView to display multiple views next to each other, we can use the $index variable inside the viewFile to achieve this. As far as i know there is no extension or out-of-the-box functionality for this, so we need to apply a little hack:

Assume we use twitter bootstrap, we have this html structure to be generated:

<div class="container">
<div class="span12">
<div class="row">
<div class="span4">
CONTENT
</div>
<div class="span4">
CONTENT
</div>
<div class="span4">
CONTENT
</div>
</div>
</div>
</div>

and so on. Do the following in your viewFile:

<?php $pageSize = $widget->dataProvider->getPagination()->pageSize; ?>
 
<?php if($index == 0) echo '<div class="row">'; ?>
<div class="span3">
 
// Your content goes here
 
</div>
 
<?php if($index != 0 && $index != $pageSize && ($index + 1) % 4 == 0)
    echo '</div><div class="row">'; ?>
 
<?php if(($index + 1) == $pageSize ) echo '</div>'; ?>

Make sure to adjust the %4 and span3 to how much columns you want

2 columns: span:6 %: 2
3 columns: span:4 %: 3
4 columns: span:3 %: 4
6 columns: span:2 %: 6

and so on.

Total 4 comments

#18698 report it
Lucky Vic at 2014/12/14 12:40am
div close tag not printed

Nice wiki! In some case if total data count less than pageSize, div close tag will not printed. So I modified condition in last div close tag to

<?php 
$totalCount  = $widget->dataProvider->totalItemCount;
if(($index + 1) == $pageSize || ($index + 1) == $totalCount) echo '</div>'; 
?>
#15370 report it
marjss at 2013/11/02 09:14am
Thanks a lot

Really you saved my day...its really very confusing task...

#14444 report it
Peter JK at 2013/08/12 09:51am
simple and useful

nice wiki ..

thx thyseus

#13357 report it
JFReyes at 2013/05/24 06:01am
There's an extension already

It's called EColumnListView but it uses tables instead of divs, so your approach is more modern and flexible. Thanks!

Leave a comment

Please to leave your comment.

Write new article