[英]how to access variables in a different controller with Cakephp
是的,我有:
Controller/PostsController.php
Model/Post.php
View/Posts/index.ctp
控制器在數據庫中找到所有帖子,然后將值傳遞到我的view / Posts / index.ctp中,在其中我逐條列出每個帖子。
我現在希望能夠訪問相同的帖子,但在另一個控制器上並查看。 我該怎么做呢?
PostsController是;
class PostsController extends AppController {
public function index() {
$this->set('posts', $this->Post->find('all'));
}
}
視圖/帖子/index.ctp是;
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Actions</th>
<th>Created</th>
</tr>
<!-- Here's where we loop through our $posts array, printing out post info -->
<?php foreach ($posts as $post): ?>
<tr>
<td><?php echo $post['Post']['id']; ?></td>
<td>
<?php
echo $this->Html->link(
$post['Post']['title']
);
?>
</td>
<td>
<?php echo $post['Post']['created']; ?>
</td>
</tr>
<?php endforeach; ?>
</table>
現在,在我的AboutsController和Abouts / index.ctp中,我希望能夠訪問相同的數據,以便可以在view / abouts / index.ctp上顯示帖子。
當我進行view / abouts / index.ctp時,具有與View / Posts / index.ctp相同的代碼,我得到錯誤消息;
Undefined variable: posts [APP\View\Abouts\index.ctp, line 12]
這是因為我不知道如何在“關於” /“控制器”中訪問數據。
對於全局變量,我建議在appController中將其設置為appController,無論您身在何處均可從中訪問它:
class AppController extends Controller {
var $uses = array('Post'); // to use the model
public function beforeFilter(){
$this->set('posts', $this->Post->find('all'));
}
}
那么您可以在任何視圖中獲取帖子...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.