Spiga

Zend Framework View Helper for Smarty Cycle

by Gabi Solomon

As i stated in a recent post i am now starting to learn Zend Framework. And with all new things that you learn, you try to find the old ways ( at least i do :D ).

So today i was trying to find a method of creating a zebra table. The old way i used to this back when i was using smarty is by using the cycle custom function. Basically it will just alternate through a set of values to create the effect.

PHP:
  1. {section name=rows loop=$data}
  2. <tr bgcolor="{cycle values="#eeeeee,#d0d0d0"}">
  3.    <td>{$data[rows]}</td>
  4. </tr>
  5. {/section}

Then when i moved on and stop using smarty, i wrote a similar function for my template engine.

So now i am looking for a similar solution on Zend Framework. Luckily for me some bright fellows have already thought of me :D .
In the zend wiki there is a Zend_View_Helper_Cycle Component Proposal that does exacly what i was wishing for :D .

Heres an example of how you can use it:

PHP:
  1. <?php $cycle=$this->cycle(array("#F0F0F0","#FFFFFF"));?>
  2. <?php foreach ($this->books as $book):?>
  3.   <tr  style="background-color:<?=$cycle->next()?>">
  4.   <td><?=$this->escape($book['author']) ?></td>
  5. </tr>
  6. <?php endforeach;?>

The proposal has been approved for development in standard/incubator.
You can download it from here.

Cheers.

Related Posts

  • Oops, missing a parens up there, should be:

    echo (is_int($this->partialCounter / 2) ? 'g' : '')
  • If, like me, you found this helpful blog while looking for a way to alternate colors while using a partialLoop, you may not need the Cycle helper. partialLoop() assigns a variable, "partialCounter", to the view, which indicates its position in the loop. So, if you need to alternate between "yes" and "no", you could do this:

    echo is_int($this->partialCounter / 2) ? 'no' : 'yes')

    Hope this helps someone!
  • i guess its a matter of choice ... for me using a helper looks more cleaner.

    PS: sorry no code tag in comments
  • I thought you might say that ;)

    In that case its no longer a 1 liner:

    http://pastebin.com/f1d84e50


    BTW, is there a code tag in your comments section available?
  • that is one option, but its a little more trickier when working with more then 2 values.
  • That didnt work out so well on my last post.. ;)

    http://pastebin.com/f161b3b1b
  • Another way to achieve this in your view scripts:

    Color Cycler:

    <? for ($i = 0; $i

    The current color is .


    Not only do you get outputting, but you also get assignment! :)

    -ralph
  • Nice work. This is definitely a useful helper... Much better than having to do ifs and all that.
blog comments powered by Disqus