Select your language
In this article, we will learn: How to create a unique slug or alias based on Title for that specific entry, using PHP and Joomla.
We need to add slug / alias functions inside controller.
<?phppublic function createSlug($title) { // Convert to lowercase $slug = strtolower($title); // Remove HTML tags $slug = strip_tags($slug); // Replace special characters with a space $slug = preg_replace('/[^\p{L}\p{Nd}]+/u', '-', $slug); // Remove multiple dashes $slug = preg_replace('/-+/', '-', $slug); // Trim dashes from the beginning and end $slug = trim($slug, '-'); return $slug; } public function generateUniqueAlias($alias, $table, $column ) { $db = Factory::getDBO(); $uniqueAlias = $alias; $suffix = 1; // Prepare the query to check for duplicates. $query = $db->getQuery(true) ->select($db->quoteName($column)) ->from($db->quoteName($table)) ->where($db->quoteName($column) . ' like ' . $db->quote($uniqueAlias)).''; // echo $query; while ($db->setQuery($query)->loadResult()) { $uniqueAlias = $alias . '-' . $suffix; $suffix++; $query = $db->getQuery(true) ->select($db->quoteName($column)) ->from($db->quoteName($table)) ->where($db->quoteName($column) . ' = ' . $db->quote($uniqueAlias)); } return $uniqueAlias; } ?>
Later we will call these functions in save function using following code to get unique slug/alias:
<?php$post['slug']=($post['slug']!="")?$post['slug']:$this->createSlug($post['txtName']); // Example usage: // Assuming $db is your database connection object in Joomla $alias = $post['slug']; $table = "#__company"; $column = "slug"; $uniqueAlias = $this->generateUniqueAlias($alias, $table, $column ); $post['slug']=$uniqueAlias;// Output : title-1, title-2, title-3 respectively, if Title is already found,
Hope this helped.
Still need help! no problem, feel free to contact us Today
Abdul Waheed : (Hire Joomla & PHP Pakistani Freelancer)