Check if object exists or is empty in view template

╄→尐↘猪︶ㄣ 提交于 2019-12-22 09:45:38

问题


How do you check within the view template if the result object contains any entries?

(There was a similar question already, but this one is slightly different)

Take the CakePHP 3 blog tutorial for example. They show how to list all articles on one page:

// src/Controller/ArticlesController.php
public function index() {
  $this->set('articles', $this->Articles->find('all'));
}

And the view template:

<!-- File: src/Template/Articles/index.ctp -->
<table>
  <tr>
    <th>Id</th>
    <th>Title</th>
  </tr>
<?php foreach ($articles as $article): ?>
  <tr>
    <td><?= $article->id ?></td>
    <td>
      <?= $this->Html->link($article->title, ['action' => 'view', $article->id]) ?>
    </td>
</tr>
<?php endforeach; ?>
</table>

Disadvantage: if there are no entries in the database the HTML table is still rendered.

How can I prevent this and show a simple message like "Sorry no results" insteat?

In CakePHP 2 I used

if ( !empty($articles['0']['id']) ) {
  // result table and foreach here
} else {
  echo '<p>Sorry no results...</p>';
}

But since $articles is now an object this doesn't work anymore... Is there a new "short way" to check the result object? Or do you usally use another foreach first, like

$there_are_results = false;
foreach ($articles as $article) {
  if ( !empty($article->id) ) {
    $there_are_results = true;
    break;
  }
}
if ( $there_are_results == true ) {
  // result table and second foreach here
} else {
  echo '<p>Sorry no results...</p>';
}

Thanks for your hints.


回答1:


You can use the iterator_count() function to know if there are results in the set:

if (iterator_count($articles)) {
 ....
}

You can also use the collection methods to get the first element:

if (collection($articles)->first()) {
}

Edit:

Since CakePHP 3.0.5 the best way to check for emptiness on a query or a result set is this:

if (!$articles->isEmpty()) {
    ...
}



回答2:


I believe you can call $articles->count() from your template. (Check for 0)




回答3:


Something I have been struggling for a while..

if(!$articles->isEmpty()) {
gives error on empty value
Call to a member function isEmpty() on null
<?php if(iterator_count($articles)) { ?>
Argument 1 passed to iterator_count() must implement interface Traversable, null given
<?php if (collection($articles)->first()) {?>
Only an array or \Traversable is allowed for Collection

I got to work, the problem if you render a different view in the controller $this->render('index'); for a function you should do that after the values has been set



来源:https://stackoverflow.com/questions/30009554/check-if-object-exists-or-is-empty-in-view-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!