Zend Passing variable to PartialLoop inside partial view
I have in my view a partial containing a partialLoop. But when I run the page I have the following error message:
Call to a member function countComments() on a non-object in ...'_loop.phtml'
This is how I call my partial from within my view:
echo $this->partia开发者_Python百科l('_post.phtml',$this->post);
where $this->post is a DB retrieved row
This is my partial's content:
MY simplified Partial!
echo $post->countComments();//the count number is correctly output..
echo $this->partialLoop('_loop.phtml',$this->object);
This is my partialLoop's content:
echo $this->object->countComments();//no output!
In the bootstrap I have set:
$view->partial()->setObjectKey('object');
$view->partialLoop()->setObjectKey('object');
Is this the right way to call partialLoops from within partials??
P.s. I var_dumped $this->object inside my partial and it is a PostRow OBJECT.I var dumped $this->object into _loop.phtml and I have 5 NULLS (standing for id,title,text,author,datetime fields of my post)
thanks
Luca
I think that the reason is that when you pass $this->post
into partial view helper like this:
$this->partial('_post.phtml',$this->post);
partial view helper will execute its toArray()
method. Hence, your $this->object
is an array and you are passing an array to your partialLoop. So, in your partialLoop you are trying to execute countComments()
on an array representing your row post object, rather than actual row object.
To avoid this, I would recommend passing variables to partial and partialLoop view helpers using array notation, e.g:
$this->partial('_post.phtml',array('post' => $this->post));
Hope this helps.
This error is caused by the default behaviour of the partial
and partialLoop
view helpers as Marcin said above.
Although it is confusing the manual does explain this here
Object implementing toArray() method. If an object is passed an has a toArray() method, the results of toArray() will be assigned to the view object as view variables.
The solution is to explicitly tell the partial to pass the object. As the manual explains:
// Tell partial to pass objects as 'model' variable
$view->partial()->setObjectKey('model');
// Tell partial to pass objects from partialLoop as 'model' variable
// in final partial view script:
$view->partialLoop()->setObjectKey('model');
This technique is particularly useful when passing Zend_Db_Table_Rowsets to partialLoop(), as you then have full access to your row objects within the view scripts, allowing you to call methods on them (such as retrieving values from parent or dependent rows).
精彩评论