我有一个表,在任何时候都可能没有任何内容可显示,一行或多行。
在我的第一次尝试中,我将变量设置为ARRAY查找ALL,但很明显,如果有1行或0行,CakePHP会抛出一个为FOREACH提供的无效参数。我可以将ARRAY查找设置为第一个,但如果有超过1行,它将只显示第一个。
有人有什么建议吗?
现场控制器中的功能:
public function add($id){
//Set Title, Stylesheet, homelogo & layout
$this->set('title_for_layout', 'View Invoices');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.png');
$this->layout='home_layout';
//Find all fields where template_id = template_id passed in
//ARRAY: to print foreach loop ONLY WORK >2 Row returned
$templatefields=$this->Field->find('all', array(
'conditions' => array(
'Field.template_id' => $id)));
//Find all fields where template_id = template_id passed in
//FIRST: to print echo variable ONLY WORK =1 Row returned
//$templatefields=$this->Field->find('first', array(
//'conditions' => array(
//'Field.template_id' => $id)));
//Set variables
$this->set('templatefields', $templatefields);
}
传入的$id是字段所属的Template id。
Fields/add.ctp.中的显示功能
<?php
if (is_array($templatefields))
{
foreach ($templatefields as $templatefield)
{
<tr>
<td align='center'><?php echo $templatefields['Field']['name']; ?></td>
<td align='center'><?php echo $templatefields['Field']['description']; ?></td>
<td align='center'><?php echo $templatefields['Field']['default_value']; ?></td>
<td align='center'><?php echo $templatefields['Field']['template_id']; ?></td>
</tr>
}
}
else if (count($templatefields)==1)
{
....print? --> WOULD HAVE TO USE $templatefields where find('first')
....otherwise error=invalid argument supplied for foreach
}
else if (empty($templatefields))
{
....NULL
....OR "There are no fields to display"
}
?>
find('all')
返回false
或Array。
因此,$templatefields
将是false
,或者始终是数组。即使它只是一个结果,它仍然是相同的格式,并且仍然是一个数组。
您的代码(已修改):
<?php
if(empty($templatefields)) {
//display "none found" message
} else {
foreach ($templatefields as $templatefield) { ?>
<tr>
<td align='center'><?php echo $templatefields['Field']['name']; ?></td>
<td align='center'><?php echo $templatefields['Field']['description']; ?></td>
<td align='center'><?php echo $templatefields['Field']['default_value']; ?></td>
<td align='center'><?php echo $templatefields['Field']['template_id']; ?></td>
</tr>
<?php }
}