0

I know there are so many questions already asked related to this issue. But mine one is little difference. I created one custom module for import the products in Magento 2. In which categories will be created automatically if not exists. Its working fine. When there is no category in store but when there is any category in store and I try to define it in csv file then I am getting "URL key for specified store already exists." error. I already checked so many answers and tried so many things but not get proper success.

4 Answers 4

2

AFAIK, You may need to delete the URL Rewrites:

MARKETING > SEO & Search > URL Rewrites

4
  • Thanks for your reply. But I don't think its good idea to remove the URL Rewrite entries. It will affect the site when we remove it?
    – Indian
    Apr 29, 2017 at 6:26
  • Yes, be careful. Seem that the url rewrites (products, categories) will be generated after running reindex. However, if you have some specific urls (cms url rewrites), they are not generated again. Apr 29, 2017 at 6:31
  • is there any way instead of delete delete the entry of URL Rewrites for resolve this issue?
    – Indian
    Apr 29, 2017 at 6:40
  • Currently, I have no idea. It's better if we take a look the Url rewrite module, try to find the root cause. Try to use Plugin or Reference to add our custom part. Or, creating our custom one. Apr 29, 2017 at 6:45
2

Just like every product, every category has a unique URL key too and you can’t have two products or categories with same URL key.

You can access the URL key of any category by selecting the category from your admin panel.

enter image description here

So when you try to add a category through CSV that already exists you’ll get the error "URL key for specified store already exists."

Make sure new categories have a unique name and a URL key.

0

After looking on internet for days I couldn't find exact solution of this. Then I found if we change the URLKEY of the category it will not show this error so I have tried this.

$category->setPath($parentCategory->getPath())
            ->setParentId($parentId)
            ->setName('test1')
            ->setIsActive(true)
            ->setUrlKey(rand(1,1000000000));
        $category->save();

I have used random function to add category in database with random nunmber using ->setUrlKey(rand(1,1000000000)); you can add any thing in this like duplicate category name with some random number etc. and errors gone if it helps you give an UP. thanks

0

I have fixed this issue in more than 3-4 projects.

If you want to resolve this issue, you can upgrade your version with latest one or try below code logic:

Try this solution by overriding below function in your custom module :)

Path: vendor/magento/module-url-rewrite/Model/Storage

protected function doReplace(array $urls){ 
    $this->deleteOldUrls($urls); 
    $data = [];
    $storeId_requestPaths = [];
    foreach ($urls as $url) {
        $storeId = $url->getStoreId();
        $requestPath = $url->getRequestPath();
        $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]);
            }
        }
    }
    try {
        $this->insertMultiple($data);
    } catch (\Magento\Framework\Exception\AlreadyExistsException $e) {
        /** @var \Magento\UrlRewrite\Service\V1\Data\UrlRewrite[] $urlConflicted */
        $urlConflicted = [];
        foreach ($urls as $url) {
            $urlFound = $this->doFindOneByData(
                [
                    UrlRewriteData::REQUEST_PATH => $url->getRequestPath(),
                    UrlRewriteData::STORE_ID => $url->getStoreId(),
                ]
            );
            if (isset($urlFound[UrlRewriteData::URL_REWRITE_ID])) {
                $urlConflicted[$urlFound[UrlRewriteData::URL_REWRITE_ID]] = $url->toArray();
            }
        }
        if ($urlConflicted) {
            throw new \Magento\UrlRewrite\Model\Exception\UrlAlreadyExistsException(
                __('URL key for specified store already exists.'),
                $e,
                $e->getCode(),
                $urlConflicted
            );
        } else {
            throw $e->getPrevious() ?: $e;
        }
    }

    return $urls;
}

Happy Coding :)

Thanks,

Ketan T.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.