Check if object exists or is empty in view template

Oops D'oh picture Oops D'oh · May 3, 2015 · Viewed 9.3k times · Source

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.

Answer

Jos&#233; Lorenzo Rodr&#237;guez picture José Lorenzo Rodríguez · May 3, 2015

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()) {
    ...
}