Forum
How to get a Unique Alias
Hi !
In Joomla 4 I have issues to create an Alias when the same Alias already exists in the database.
In my Database, it's fine, I already created the unique Alias, as explained in your example :
"CREATE UNIQUE INDEX `aliasindex` ON `#__planets` (`alias`);"
On the page https://www.techfry.com/joomla/add-alias-field-to-joomla-component
you wrote :
"You have to make sure that the alias is unique, and doesn't contain characters that aren't allowed in the URLs."
Then you mentioned :
"You can do this by overriding the Table::check() method. "
Can you provide the code for this ?
In my own code, if the Alias already exists in the database I have : " Duplicate entry 'concert-au-3-arena' for key 'aliasindex'"
How can I solve this ?
Thanks
You have to check for duplicate alias before saving record. You can do this in Table class or Model file before saving the record.
Just query the database table to find item with the alias. If the record is found, then you can change the alias before saving or display some message like record already exists.
Here is the method you are looking for and we use in our extensions. The get_item() method searches the record for the given alias in the table. If alias is found, the method appends a number at the end.
public function check_alias($alias, $id, $table_name)
{
$current_alias = $alias;
$found = 0;
$i = 2;
do
{
$item = $this->get_item($table_name, $alias, 'alias');
if ($item && ($item->id != $id))
{
$alias = $current_alias . '-' . $i;
$found = 1;
$i++;
}
else
{
$found = 0;
}
} while ($found);
return $alias;
}
You can put this method after generating the alias - either in table file or in model file before saving the record. Both will work.
if ($data['alias'] == null)
{
if (Factory::getConfig()->get('unicodeslugs') == 1)
{
$data['alias'] = OutputFilter::stringURLUnicodeSlug($data['title']);
}
else
{
$data['alias'] = OutputFilter::stringURLSafe($data['title']);
}
}
// Check for duplicate alias
$data['alias'] = $this->check_alias($data['alias'], $data['id'], $table_name);