views:

160

answers:

3

In my controller I have model operations that can return empty results. I've setup the view to display the results using a foreach loop. But if the model opertion is empty and returns no results then the foreach loop is breaking in my view.

This is the operation:

$match3 = $this->Draw->Match-> find('all',array('conditions'=>array('Match.draw_id'=>$id, 'Match.round_id'=> 1, 'Match.match_position' => 3)));

What do I need to add to the model operation to return null? Or is null the best way to handle this?

If there is no data then I don't want anything displayed.

I did try this but got an undefined index error:

if (!$match3) return null; else return $match3;

Is there a best practice when it comes to handling empty model operations?

Much appreciated. -Paul

+1  A: 

If your find operation has no results, it will just return an empty array.

In your view, just put some logic to make sure that $match3 isn't an empty array before you output that section. E.g., in the view

<?php
 // some code here to output part of the page
 if( !empty( $match3 ) )
  foreach( $match3 as $matches )
   ; // do something with $matches
 // rest of your view code
?>
Travis Leleu
+2  A: 

IMO, the "best practice" isn't CakePHP-specific. If your result set it empty, it's critical to inform your users of that fact. It's a simple test (in this case for an empty array as indicated by Travis) and a simple result. I typically do it like this in my views:

<?php if( empty( $match3 ) ): ?>
  <h2>Display an appropriate empty set message.</h2>
<?php else: ?>
  # do whatever you need to do to display the result set
<?php endif; ?>
Rob Wilkerson
A: 

Very much depending on your app, the following responses may be appropriate:

$result = $this->Model->find(…);

if (!$result) {
    // redirect to another page and display message
    $this->Session->setFlash('No results found');
    $this->redirect(array('action' => 'index'));
}

or

if (!$result) {
    // throw a 404 (or any other) error
    $this->cakeError('error404');
}

Again, this very much depends on the app and the action in question, especially a 404 should not be a standard response. In many cases it's probably best to handle it in the view as advised by Rob.

deceze