Frontend List of Items

The concept of displaying the list of items at the frontend is very similar to displaying the list of items at the backend. The View file gets the items from the Model and then the Layout file displays the list of items. You can display in tabular layout or blog layout or any other layout.

Step 1: Model File

site/src/Model/PlanetsModel.php

In the frontend, we only get published items, so add a condition in the where clause in the getListQuery() method.

protected function getListQuery()
{
   $db = $this->getDatabase();
        
    $query = $db->getQuery(true);
        
    $query->select('*')
        ->from($db->quoteName('#__planets'))
        ->where($db->quoteName('published') . ' = ' . $db->quote(1));
            
    $query->order('id DESC');
        
    return $query;
}

Step 2: View File

site/src/View/Planets/HtmlView.php

In the view file, get the data from the Model in the display() method.

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

The above code will call the getItems() method defined in the model file.

Step 3: Layout File

site/tmpl/planets/default.php

The layout file displays the items using foreach loop. For each item, create the link to the single item and make the title as link.

<h1>Planets</h1> 
<table class="table table-striped table-hover">
  <?php foreach ($this->items as $i => $item) : ?>
      <?php $link = Route::_('index.php?option=com_stars&view=planet&id=' . (int) $item->id); ?>
        <tr>
          <td><a href="/<?php echo $link; ?>"><?php echo $item->title; ?></a></td>
        </tr>
    <?php endforeach; ?>
</table>

Step 4: Layout XML File

site/tmpl/planets/default.xml

Add XML file for the layout, so that a menu item can be created from the backend to display the list of items.

<?xml version="1.0" encoding="UTF-8"?>
<metadata>
    <layout title="Planets List">
        <message>Displays a list of planets.</message>
    </layout>
</metadata>

You can test it by creating a menu item from the Joomla! administrator.