Chapter 7 find() function

4 messages Options
Embed this post
Permalink
Anthony

Chapter 7 find() function

Reply Threaded More More options
Print post
Permalink
I'm going through the book and everything is going great up until Chapter 7 when I start dealing with the find() funtion. In pages 93-96 you say to replace:

function index() {
        $this->Post->recursive = 0;
        $this->set('posts', $this->paginate());
}

with this:

function index() {
        $this->Post->find('all',array('order'=>'date DESC','limit'=>5,'recursive'=>0));
}

in the posts_controllers.php file. Then to replace the Index action with:
<? foreach($posts as $post): ?>
<div class="story">
<?=$html->link('<h1>'.$post['Post']['name'].'</h1>','/posts/view/'.$post['Post']['id'],null,null,false);?>
<p>Posted<?=date('MjSY,g:ia',strtotime($post['Post']['date']));?></p>
<p>By<?=$post['User']['firstname'];?> <?=$post['User']['lastname'];?> </p>
<br/>
<p><?=$post['Post']['content'];?></p>
</div>
<?endforeach; ?>

Which gives me the following error: Undefined variable: posts [APP/views/posts/index.ctp, line 1]

Looking in the source code you've provided, the index function in the posts_controllers.php file is the same as Chapter 6. Any help?
davidgolding

Re: Chapter 7 find() function

Reply Threaded More More options
Print post
Permalink
The function needs to look like:

$posts = $this->Post->find('all',array('order'=>'date DESC', 'limit'=>5, 'recursive'=>0));

and don't forget to pass the variable to the view with:

$this->set('posts',$posts);
--Dave

Author, "Beginning CakePHP: From Novice to Professional"

[ get your copy at: http://www.amazon.com/Beginning-CakePHP-Novice-Professional/dp/1430209771/ ]
Anthony

Re: Chapter 7 find() function

Reply Threaded More More options
Print post
Permalink
Thanks David, it's working great.

Did I miss that somewhere in the book?
davidgolding

Re: Chapter 7 find() function

Reply Threaded More More options
Print post
Permalink
In that section I describe how to use the model find() function to return records from the database. I assume that the reader is aware of what's happening in the $this->set() function to know how to substitute the find() function for paginate(). I could have been more clear in the tutorial instructions on what to do with that function in the working example.
--Dave

Author, "Beginning CakePHP: From Novice to Professional"

[ get your copy at: http://www.amazon.com/Beginning-CakePHP-Novice-Professional/dp/1430209771/ ]