How to Link Joomla Categories Component

You can link Joomla! Categories functionality in your custom component where you can define a set of categories to use. This way, you don't need separate categories table for your component.

You need to do following things:

  1. Create a new field in the database to link with the categories table: catid.
  2. Add a select box to the edit form (XML Form), so that administrators can add category to items.
  3. Add a sub menu link to add and manage categories.
  4. Display the category to the list of items.

1. Modify Database Table

You need a field column catid in your database table of items, for which you need to add categories functionality.

catid int(11) NOT NULL DEFAULT 0

Add in the install SQL file or update file accordingly.

2. Edit XML Form

Your items can now belong to a category. So, you need to modify the editing XML form. Add a new category type field.

<field
name="catid"
type="category"
extension="com_stars"
label="JCATEGORY"
required="true">
<option value="0">JOPTION_SELECT_CATEGORY</option>
</field>

The category can have catid of 0, which represents no category.

3. Add Sub Menu Link

You set the sub menu for categories in component XML file.

<menu link="option=com_categories&amp;extension=com_stars">COM_STARS_CATEGORIES</menu>

4. Display Category in List View

You need to modify the getListQuery() method and use SQL join with the Joomla Categories table to find the associated category title. The name of the category is stored in #__categories table and category Id is stored in table of your component.

$query->select('a.id as id, a.title as title, a.published as published')
->from($db->quoteName('#__planets', 'a'));

// Join over the categories
$query->select($db->quoteName('c.title', 'category_title'))
->join('LEFT', $db->quoteName('#__categories', 'c') . ' ON c.id = a.catid');

In your layout template file, you can display category title below the title of the item or as a separate column.

<td>
<a href="/<?php echo $link; ?>" title="<?php echo Text::_('JGLOBAL_EDIT_ITEM'); ?>">
<?php echo $row->title; ?>
</a>
<div class="small">
<?php echo Text::_('JCATEGORY') . ': ' . $this->escape($row->category_title); ?>
</div>
</td>