CakePHP Zebra Striped Tables

The following code sample will add an ‘altrow’ class to every alternative row in a table with a minumum overhead. The code produced is compatible with the default cake.generic.css stylesheet:


<?php foreach ($upcoming_events as $i=>$event) { ?>
<tr<?php echo ($i % 2 == 0) ? " class='altrow'" : "" ?>>
.. table td's go here
</tr>
<?php } ?>

The ‘trick’ is changing the usual foreach():


<?php foreach ($upcoming_events as $event) { ?>

…to return the row index ($i). That value is then modded (%) with 2 (divided by 2, ignore remainders) to return a value of 1 or 0 to determine if the row is odd or even.

Tagged with:
Posted in CakePHP, CSS, PHP
3 comments on “CakePHP Zebra Striped Tables
  1. Eddie Webb says:

    Nice trick.

    Do the variable calls still work as usual, or does the index need to be added there as well.

    ie
    $event[‘Model’][‘field’] //VS.
    $upcomming_events[$i][‘MOdel’][‘field’] ?

  2. Richard@Home says:

    Hi Eddie, you can still use the same code inside the loop as usual,

    e,g.

    echo $event[‘Event’][‘name’];

  3. prakash says:

    sir,

    please advise how to use the above logic with the ‘TABLEHEADERS’ and ‘TABLECELLS’ functions of the HTML helper of cakephp 1.2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: