Magento 2: How to generate Product URL Key when creating Product from Rest API?
I have created a custom code to check if the URL key exists or not. As per the flow used in product import functionality in Magento 2.
public function __construct(
--
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\App\ResourceConnection $resource,
--
) {
--
$this->_storeManager = $storeManager;
$this->_resource = $resource;
--
}
public function createUrlKey($title, $sku)
{
$url = preg_replace('#[^0-9a-z]+#i', '-', $title);
$urlKey = strtolower($url);
$storeId = (int) $this->_storeManager->getStore()->getStoreId();
$isUnique = $this->checkUrlKeyDuplicates($sku, $urlKey, $storeId);
if ($isUnique) {
return $urlKey;
} else {
return $urlKey . '-' . time();
}
}
/*
* Function to check URL Key Duplicates in Database
*/
private function checkUrlKeyDuplicates($sku, $urlKey, $storeId)
{
$urlKey .= '.html';
$connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);
$tablename = $connection->getTableName('url_rewrite');
$sql = $connection->select()->from(
['url_rewrite' => $connection->getTableName('url_rewrite')], ['request_path', 'store_id']
)->joinLeft(
['cpe' => $connection->getTableName('catalog_product_entity')], "cpe.entity_id = url_rewrite.entity_id"
)->where('request_path IN (?)', $urlKey)
->where('store_id IN (?)', $storeId)
->where('cpe.sku not in (?)', $sku);
$urlKeyDuplicates = $connection->fetchAssoc($sql);
if (!empty($urlKeyDuplicates)) {
return false;
} else {
return true;
}
}
To perform the CreateUrlKey function, I added at the second line this code:
$lastCharTitle = substr($title, -1);
$lastUrlChar = substr($url, -1);
if ($lastUrlChar == "-" && $lastCharTitle != "-"){
$url = substr($url, 0, strlen($url) - 1);
}
to remove the last "-" if this is generated from the first line "preg_replace". Also i've replaced the timestamp with the unique Sku,becose sometime in the automated import process the time() of two adjacent records can be the same, so it isn't unique.
Now the function is:
public function createUrlKey($title, $sku)
{
$url = preg_replace('#[^0-9a-z]+#i', '-', $title);
$lastCharTitle = substr($title, -1);
$lastUrlChar = substr($url, -1);
if ($lastUrlChar == "-" && $lastCharTitle != "-"){
$url = substr($url, 0, strlen($url) - 1);
}
$urlKey = strtolower($url);
$storeId = (int) $this->_storeManager->getStore()->getStoreId();
$isUnique = $this->checkUrlKeyDuplicates($sku, $urlKey, $storeId);
if ($isUnique) {
return $urlKey;
} else {
return $urlKey . '-' . $sku;
}
}