Add Alias Field to Joomla Component

An alias field is required for SEF (Search Engine Friendly) URLs for accessing items on the website. SEF URLs are helpful for to both humans and search engines.

For example, if there is a database of planets, then SEF URL would be something like:

https://example.com/galaxy/planets/venus

instead of something like

https://example.com/galaxy?catid=37&id=52

You can switch SEF URLs on or off through the Joomla Global Configuration, Site tab, SEO Settings.

Step 1: Database Field

First, define the alias field to be not null and unique. To add the alias field to the database record.

`alias` VARCHAR(400) NOT NULL DEFAULT '',

For existing tables,

ALTER TABLE `#__planets` ADD COLUMN `alias` VARCHAR(400) NOT NULL DEFAULT '';

Then, create unique index:

CREATE UNIQUE INDEX `aliasindex` ON `#__planets` (`alias`);

Step 2: XML Form

forms/planet.xml

Next, add alias field to the backend XML form:

<field 
    name="alias"
    type="text"
    label="JFIELD_ALIAS_LABEL"
    hint="JFIELD_ALIAS_PLACEHOLDER" />

Step 3: Layout File

tmpl/planets/default.php

You can  display the alias in the backend list layout below the title. Add the following code just after the link tag on the title.

<div class="small break-word">
    <?php echo Text::sprintf('JGLOBAL_LIST_ALIAS', $this->escape($row->alias)); ?>
</div>

Step 4: Save Alias Automatically

You have to make sure that the alias is unique, and doesn't contain characters that aren't allowed in the URLs.

Option 1: src/Table/PlanetTable.php

You can do this by overriding the Table::check() method. The check() is called before saving the record. Hence, you can override this to ensure that the alias field is not blank and has bad characters are stripped out. 

This will check both records entered via the admin form, and those entered via the front-end form. The unique index will ensure that alias values are not duplicated.

Option 2: src/Model/PlanetModel.php

Another option is to generate the alias in the save() method of model file before saving the record.

if (empty($data['alias']))
{
    if (Factory::getConfig()->get('unicodeslugs') == 1)
  {
      $data['alias'] = OutputFilter::stringURLUnicodeSlug($data['title']);
  }
    else
  {
      $data['alias'] = OutputFilter::stringURLSafe($data['title']);
  }
}

After adding the alias field, you can create router for the component.