可能重复:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”发送变量到视图从控制器蛋糕不工作
在我的意见控制器,我有以下方法:
public function popularTabs() {
$this->set('hour', $this->popularToday()); // send hour
$this->set('today', $this->popularHour()); // send day
}
我打算将变量'hour'和'today'发送到视图。这些都发送一个数组,其中包含来自popularToday()和popularHour()方法的数据,这些数据在私有方法中定义在同一个控制器中。它们看起来像:
private function popularHour() {
return $submissions = $this->Submission->find('all', array(
'conditions' => array('Submission.approved' => '1'),
'order' => 'Submission.created DESC'
));
}
里面我认为,所谓的popular.ctp的,我做了检查,看是否参数包含小时或今天,并显示相应的数据通过调用它基本上只是格式元素它符合我的喜好(元素在其他地方正确显示,所以没有问题)。
该视图(popular_tabs.ctp)的代码是:
if ($this->params['pass'][0] == 'hour') {
// Set our $hour variable to $submissions, which is what the
// foreach loop inside single_submission_entry uses as a variable
// to loop through
$submissions = $hour;
echo $this->element('single_submission_entry', $hour);
}
if ($this->params['pass'][0] == 'today') {
$submissions = $hour;
echo $this->element('single_submission_entry', $today);
}
出于某种原因,虽然,除非在popularTabs()
方法中,如果我的变量设置为任何大于提交例如OTHER
$this->set('submissions', $this->popularToday()); // send hour
它将无法正确显示。如果我尝试设置变量来小时,还是今天,它会给我下面的输出:
Notice (8): Undefined variable: submissions [APP/views/elements/single_submission_entry.ctp, line 1]
Warning (2): Invalid argument supplied for foreach() [APP/views/elements/single_submission_entry.ctp, line 1]
线single_submission_entry
1:
<? foreach ($submissions as $count => $submission): ?>
// display submission stuff here
<? endforeach; ?>
其中我特别是将$小时重命名为$提交...所以我不确定我在这里错过了什么?
如果我从我的视图(popular_tabs.ctp)内部输入print_r($ hour),它会发送正确的数据,为什么它没有正确发送到single_submission_entry?
哇。这让我疯狂。非常感谢! – 2012-02-05 05:32:10
不客气!第二个参数基本上作为元素的'this-> set()'。 – 2012-02-05 05:34:35