Recently, I have been using view script partials (Zend_View_Helper_Partial) and wanted to assign an object as an object to a partial and have full use of it in the partial. I found the solution in the ZF manual very impractical and thought of another way to solve this. In this post I describe the ‘ZF manual’ way to do it, and my easier way.

The object I wanted to assign was an instance of Zend Form assigned to the view on the key ‘commentForm’. Of course without reading the documentation, this is what I put in the view script where I wanted to include the partial:

<?php echo $this->partial('blogpost/new-comment.phtml', $this->commentForm); ?>

This didn’t work, as I found out that the object contained in $this-commentForm was converted to array and assigned as properties to the view instance of the partial. This is done either by calling toArray() on the object if the method exists, or by using get_object_vars on the object.

This is not what I wanted. I wanted to have full use of my form object in my partial. When I finally did read the manual entry about partials, I found that there was actually a way to do this, but not a very practical way. You call the method setObjectKey(‘keyname’) on the partial helper like so:

<?php $this->partial()->setObjectKey('commentForm'); ?>

If you do this first and then assign an object to a partial as above, the object gets assigned to the view instance of the partial on the key we set with setObjectKey(). Thus, we have full use of the object in the partial.

There are a couple of drawbacks to this way of doing it. First, it is irritating that I have to call setObjectKey() every time I want to do this. Second, the view script becomes less readable if I have to include this kind of code. Third, but I have yet to test this, it seems to me that the object key is set for all partials when you use setObjectKey(). This may have some unwanted side effects if you are not careful.

Here is my solution to this ‘problem’. In my eyes, it makes setObjectKey obsolete. Why not just assign an array to the partial, containing my form object like this:

<?php echo $this->partial('blogpost/new-comment.phtml', array('commentForm' => $this->commentForm)); ?>

I know, it is too simple. So simple even, that I overlooked this possibility at first. And the manual doesn’t help. The result is that I have found many posts on blogs and forums about this problem and the usage of setObjectKey(). I hope this post will be helpful to some of them.