How to Get List of Items in Joomla

While developing extensions, you need to query the database and display list of items. Joomla! provides an easy way to achieve this. The view file gets the items from the model and then the layout file displays the list of items in tabular format.

The "Planets" (default) View that we have created earlier should display the list of records or items.

Step 1: View File


The View file gets the data from the model in the display() method.

$this->items = $this->get('Items');

The above code will look for the method getItems() in the model file.

Step 2: Model File


In Joomla!, there is a class that is able to manage a list of data: ListModel. This class has already defined methods, getItems() and getPagination(). So, you are not required to define them again.

The method getItems() calls another protected method getListQuery() for the database query. You have to define this method in the model class.

protected function getListQuery()
  $db = $this->getDatabase();
  $query = $db->getQuery(true);
  // Select statement
      ->from($db->quoteName('#__planets', 'a'));
  // Order by
  $query->order(' DESC');
  return $query;

The class ListModel and inherited classes need only one method: getListQuery which constructs an SQL query. This method returns the query.

Step 3: Layout File


You can access and display the data in the layout file, default.php using foreach loop.

<table class="table table-striped table-hover">
      <?php foreach ($this->items as $i => $item) : ?>
              <td><?php echo $item->title; ?></td>
              <td><?php echo $item->id; ?></td>
      <?php endforeach; ?>

In the next, we will wrap this table within the form. So, that the toolbar actions (like new, publish, delete and so on) can work.