I just experienced some problems using an iteratable object like Zend_Db_Table_Rowset with Zend_View‘s PartialLoop helper. What happens internally is that the Partial helper (that PartialLoop uses) converts the object we want to iterate on to an array using the object’s toArray method (if it exists). Now, that’s fine if you only want to access the properties of the object. The methods simply disappear…
I looked in the docs about this but found nothing. After some searching on the fw-mvc list I found a link to ZF’s issue tracker: http://framework.zend.com/issues/browse/ZF-2431
Let’s say we want to loop through a list of names and phone numbers. We have a view script called index.phtml that contain the following code:
<h1>People</h1> <table> <?= $this->partialLoop('partials/_person.phtml', $this->people) ?> </table>
$this->people is in this case a Zend_Db_Table_Rowset object that contain several Person objects (which extends Zend_Db_Table_Row). The _person.phtml script looks like this:
<tr> <td><?= $this->name ?></td> <td><?= $this->phoneNumber ?></td> </tr>
So far so good. Now, if the Person object has a method called getFather() that returns another Person object, and want to use that in _person.phtml we will experience some problems. If we change the _person.phtml script to look like:
<tr> <td><?= $this->name ?></td> <td><?= $this->phoneNumber ?></td> <td>Father: <?= $this->getFather()->name ?></td> </tr>
and refresh the page we will get the following error:
helper ‘GetFather’ not found in path
As you can see the Person::getFather method has disappeared and since $this refers to the current view object, it thinks getFather is a view helper. I can’t remember when my father helped me with my view scripts, but that’s a different story!
How to fix this you ask? This is where the Zend_View_Helper_Partial::setObjectKey() method comes into play! If you have set an object key using that method on the PartialLoop helper and loop an object, you have to access the object in the partial loop script using the same object key you specified in the setObjectKey() call. Confused? Nothing that a little code can’t fix!
If you want to use the same object key in all your partial loop scripts, you can set the object key in your bootstrapper doing something like this:
$view = new Zend_View(); $view->partialLoop()->setObjectKey('object'); $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer'); $viewRenderer->setView($view);
Now we also need to change the _person.phtml script to access the object in a slightly different manner:
<tr> <td><?= $this->object->name ?></td> <td><?= $this->object->phoneNumber ?></td> <td>Father: <?= $this->object->getFather()->name ?></td> </tr>
Refresh, and the people in the list will have a father!