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

src/View/Planets/HtmlView.php

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

src/Model/PlanetsModel.php

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
  $query->select('*')
      ->from($db->quoteName('#__planets', 'a'));
     
  // Order by
  $query->order('a.id 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

tmpl/planets/default.php

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

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

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.