I create a simple blog with cakephp where i have some posts and some comments.
After i bake an application it create a comments folder with the index.ctp and a posts folder with the index.ctp
What i want to do is display them as fallow:
Post1
comment1
comment2
Post2
comment1
comment2
If i place the comments inside the posts/index.ctp i get an error telling me that the $comments is not defined.
How can i do this?
Thanks
edit:
alright, im sorry for the comeback, but it’s still a bit unclear. I do have the $hasMany relationship setup, in fact on the page that displays the posts i have a link that points me to the comments. The only thing that i want them to be displayed in the same page as the posts.
i should be able to say <?php echo $comment['Comment']['content']; ?>
Check your controllers.
If you want to display Comment information in a Posts view, you need to be sure that the Posts controller can load the data.
The “CakePHP” way is to define relationships between models. Check your baked models and see if there is something like this:
When the models are associated with each other, your Posts controller will automatically find Post objects and their associated Comment objects.
For instance, this line:
Will produce something like this:
Good documentation at http://book.cakephp.org/
EDIT: Adding more info after your comment
As long as the models have the association, CakePHP will pull the data appropriately (unless you set
Recursive => falseor are usingContainablewhich I assume you aren’t).Check your PostsController controller and see how it’s loading the data. I’m guessing it is doing something like the following:
or
Check which way it is storing the retrieved data, and then access that variable from the view.
For example, if it is storing the data in a variable named “$post”, you would put something like this in your view:
By default CakePHP stashes tons of detail in arrays after retrieving data. The trick is to know the hierarchy of the data and fetch it from the array accordingly.