Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if object exists or is empty in view template

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.

like image 757
Oops D'oh Avatar asked Nov 28 '22 01:11

Oops D'oh


2 Answers

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()) {
    ...
}
like image 81
José Lorenzo Rodríguez Avatar answered Dec 11 '22 01:12

José Lorenzo Rodríguez


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

like image 42
Keylan Avatar answered Dec 11 '22 01:12

Keylan