php - CakePHP 将数据传递给元素

标签 php cakephp

我的 Controller 中有以下代码:

function index()
{
    $posts = $this->set('posts', $this->Portfolio->find('all'));

    if (isset($this->params['requested']))
    {
        return $posts;
    }
    else
    {
        $this->set('posts', $this->Portfolio->find('all'));
    }
}

我想要它做的是a)显示索引的投资组合项目列表,例如/portfolio/ 和 b) 在元素内显示投资组合项目列表,以便用户可以从整个网站的侧边栏访问投资组合项目。

这是我的侧边栏元素:

<?php $posts = $this->requestAction('portfolio/index'); ?>
<ul>
    <?php foreach ($posts as $post): ?>
    <li><?php echo $this->Html->link($post['Portfolio']['title'], array('action' => 'view', $post['Portfolio']['id']));?></li>
    <?php endforeach; ?>
</ul>

然后我在布局中这样调用它:

<?php $this->element('portfolio-nav', array('posts' => $posts) ); ?>

但是它给出了以下错误:

Notice (8): Undefined variable: posts [APP/controllers/portfolio_controller.php, line 16]

并且不在侧边栏中显示项目列表。

我很确定我在 Controller 中编写的内容是垃圾,所以如果有人可以帮助我让它工作,那就太棒了。

谢谢

最佳答案

我昨天回答了同样的问题。为什么你的 Controller Action 如此复杂?我想你只需要

function index() {
    $this->set('posts', $this->Portfolio->find('all'));
    // Make sure the model Portfolio is accessible from here, i.e. place this
    // action in PortfoliosController or load it using 
    // ClassRegistry::init('Portfolio')->find... 
}

然后,在您的index.ctp View 中:

<?php echo $this->element('foobar', array('posts' => $posts)); ?>

如果您希望能够从站点中的每个页面(侧边栏或其他内容)请求此操作,您可以使用 requestAction,或将 $this->set... 在你的 AppController 中。如果您在元素中使用 requestAction,则不必在 $this->element 中传递 array('posts' => ...) 调用。

<小时/>

好的,很明显您需要更多指导。让我一步一步解释这一点。首先,我们需要在您的 AppController 上创建一个 beforeFilter,以便可以从应用程序中的任何位置访问 $posts 变量。

/app/app_controller.php:

<?php
class AppController extends Controller {
    function beforeFilter() {
        parent::beforeFilter();
        $this->set('posts', ClassRegistry::init('Portfolio')->find('all'));
    }
}

接下来,我们在 app/views/elements/foobar.ctp 中创建一个简单的元素:

<?php debug($items); ?>

最后,我们从 View 中的某个位置调用该元素:

<?php echo $this->element('foobar', array('items' => $posts)); ?>

我们正在为 $posts(我们在 AppController 中定义)变量分配 items 键,因为我们的元素需要一个 $items 变量。

关于php - CakePHP 将数据传递给元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5523162/

相关文章:

php - 使用 ini_set ("memory_limit", "-1")并且仍然内存不足

php - Symfony 在一个字段中形成 2 种不同的值类型

mysql - CakePHP 按日期范围查找?

mysql - 如何使用 CakePHP 截断表?

php - 如何启用 gzip?

php url 检查可用

php - Ajax 与 jquery 设置时间间隔

php - 在另一个表中发生不相关的插入操作后,Mysql 行被删除

mysql - CakePHP 1.3 - 在模型查询中使用 RLIKE

php - 如何在 cakephp 3 中获取最近每小时/每天/每周/每年间隔的总计数?