Question

When creating products in Magento 1 the url was created from the product name, and if there were duplicate product names M1 would add a numerical suffix to the end of the URL.

Since it seems this is no longer the case in Magento 2, how do I deal with products with the same name having duplicate URLs and causing an error?

Thanks

Was it helpful?

Solution

Found 2 solutions for that:

  1. Clean up your database in table url_rewrite. You can write UpgradeData script for this solution.(Make sure you took the database backup)
  2. The second one: Remove the duplication data when saving category. This data is throw in method doReplace($urls) in \vendor\magento\module-url-rewrite\Model\Storage\DbStorage.php file.

    protected function doReplace($urls)
    {
        foreach ($this->createFilterDataBasedOnUrls($urls) as $type => $urlData) {
            $urlData[UrlRewrite::ENTITY_TYPE] = $type;
            $this->deleteByData($urlData);
        }
        $data = [];
        foreach ($urls as $url) {
            $data[] = $url->toArray();
        }
        $this->insertMultiple($data);
    } 
    

After debugging, I found out $data variable has a duplicate record. If you want this method to work without any errors. Rewrite this method above to:

    protected function doReplace($urls) {
        foreach ($this->createFilterDataBasedOnUrls($urls) as $type => $urlData) {
            $urlData[UrlRewrite::ENTITY_TYPE] = $type;
            $this->deleteByData($urlData);
        }
        $data = [];
        $storeId_requestPaths = [];
        foreach ($urls as $url) {
            $storeId = $url->getStoreId();
            $requestPath = $url->getRequestPath();
            // Skip if is exist in the database
            $sql = "SELECT * FROM url_rewrite where store_id = $storeId and request_path = '$requestPath'";
            $exists = $this->connection->fetchOne($sql);

            if ($exists) continue;

            $storeId_requestPaths[] = $storeId . '-' . $requestPath;
            $data[] = $url->toArray();
        }

        // Remove duplication data;
        $n = count($storeId_requestPaths);
        for ($i = 0; $i < $n - 1; $i++) {
            for ($j = $i + 1; $j < $n; $j++) {
                if ($storeId_requestPaths[$i] == $storeId_requestPaths[$j]) {
                    unset($data[$j]);
                }
            }
        }
        $this->insertMultiple($data); }

If you want to get more details. Please, read comment in

https://github.com/magento/magento2/issues/7298

Hope this will help you.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top