1

我有一张桌子,在任何时候都可能没有任何东西可以显示,一行或多行。

在我的第一次尝试中,我将变量设置为查找 ALL 的数组,但显然如果有 1 行或 0 行,CakePHP 会抛出为 FOREACH 提供的无效参数。我可以设置 ARRAY 查找 FIRST,但如果有超过 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"
}
?>
4

1 回答 1

3

find('all')返回一个false或一个数组。

因此,$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 }
}
于 2012-08-22T16:58:30.647 回答