Monday, April 22, 2013

Handle potential plural items

Let's say you have a count of items ("widgets") that you want to display.

When you count them, the result could be 0, 1, or more than 1 item.  SO you need to display one of the following:

  • 0 widgets
  • 1 widget
  • 2 widgets

In PHP, you can handle this with the following code:

<?php print $view->total_rows;
 if ($view->total_rows == 1) {
   print " widget"; 
} else {
   print " widgets";
}
 ?> 


Or use Drupals built in function "format_plural" to help out:
<?php print format_plural(max(0, $view->total_rows), '1 widget', '@count widgets'); ?>

No comments:

Post a Comment