我正在使用cakephp,并试图检查表中是否输入了数据。如果没有数据,则显示一条消息,说"没有数据"。如果有数据,显示出来。
我可以很好地显示结果,我只是不知道如何告诉cakepp检查表中是否有任何信息。
我是否将检查模型的逻辑放在视图中,并引用该模型函数?一般来说,我对cakepp和MVC都是新手,所以我仍在尝试掌握数据流的窍门。
编辑-这是我的索引文件代码。当我只列出$myports而没有函数时,我收到了以下错误。
分析错误:语法错误,意外的T_VARIABLE,在…中应为T_FUNCTION
<h1>Sorted Entries</h1>
<?php
echo $this->Html->link("Add List", array('action' => 'add'));
if (!empty($mysorts)) {
?>
<table>
<tr>
<th>ID</th>
<th>Original</th>
<th>Sorted</th>
</tr>
<?php foreach ($mysorts as $mysort): ?>
<tr>
<td><?php echo $mysort['Mysort']['id']; ?></td>
<td>
<?php echo $mysort['Mysort']['original']; ?>
</td>
<td> <?php echo $mysort['Mysort']['sorted']; ?>
</td>
</tr>
<?php endforeach;
} else {
echo '<p>No results found!</p>';
}
?>
</table>
这是我的控制器
class MysortsController extends AppController {
public $helpers = array('Html', 'Form');
public function index() {
$this ->set('mysorts', $this->Mysort->find('all'));
}
public function add() {
if($this->request->is('post')) {
$this->Session->setFlash('yes');
$this->redirect(array('action' => 'index'));
}
}
function isempty(){
$mysorts = $this->Mysort->find('all');
$this->set('mysorts', $mysorts);
}
}
?>
假设
$mysorts = $this->Mysort->find('all');
$this->set('mysorts', $mysorts);
在控制器中,然后您可以查看视图:
if (!empty($mysorts) {
// table and foreach loop
} else {
echo '<p>No results found!</p>';
}
如果您想使用视图中的任何控制器方法,您可以使用requestAction
$result = $this->requestAction(array(
'controller' => 'mycontroller',
'action' => 'action')
); // $result will have return value from your action
echo $this->requestAction(array(
'controller' => 'mycontroller',
'action' => 'action'),
array('return')
); // will return rendered view
请求操作一直是是否应该使用它的争论主题。有人说将其与缓存一起使用不会对性能造成太大影响,也有人说这是明智之举。不久前,我浏览了一篇帖子,上面说"请求行动"并没有大家预期的那么糟糕。
尽管如此,还是要避免使用此选项。我更喜欢对控制器进行ajax调用。