1

when I have the category in product assign and saving category below error showing

The value specified in the URL Key field would generate a URL that already exists.

To resolve this conflict, you can either change the value of the URL Key field (located in the Search Engine Optimization section) to a unique value or change the Request Path fields in all locations listed below:

enter image description here

and my exception.log error log is

enter image description here

  • You have duplicate URLs. – vitoriodachef Jun 21 at 9:07
  • @vitoriodachef but how can solve this issue – Rakesh Donga Jun 21 at 9:09
  • @vitoriodachef and exception.log is URL key for specified store already exists. – Rakesh Donga Jun 21 at 9:20
  • Wich magento version are you using? – Chirag Patel Jun 21 at 9:29
  • @ChiragPatel magento 2.2.4 – Rakesh Donga Jun 21 at 9:29
0

Please override with below two files : module-catalog-url-rewrite/Model/Product/AnchorUrlRewriteGenerator.php (Line 58)

/**
 * Generate list based on categories
 *
 * @param int $storeId
 * @param Product $product
 * @param ObjectRegistry $productCategories
 * @return UrlRewrite[]
 */
 public function generate($storeId, Product $product, ObjectRegistry $productCategories)
 {
 $urls = [];
 foreach ($productCategories->getList() as $category) {
 $anchorCategoryIds = $category->getAnchorsAbove();
 if ($anchorCategoryIds) {
 foreach ($anchorCategoryIds as $anchorCategoryId) {
 //Default: $anchorCategory = $this->categoryRepository->get($anchorCategoryId);
 $anchorCategory = $this->categoryRepository->get($anchorCategoryId, $storeId);
 $urls[] = $this->urlRewriteFactory->create()
 ->setEntityType(ProductUrlRewriteGenerator::ENTITY_TYPE)
 ->setEntityId($product->getId())
 ->setRequestPath(
 $this->urlPathGenerator->getUrlPathWithSuffix(
 $product,
 $storeId,
 $anchorCategory
 )
 )
 ->setTargetPath(
 $this->urlPathGenerator->getCanonicalUrlPath(
 $product,
 $anchorCategory
 )
 )
 ->setStoreId($storeId)
 ->setMetadata(['category_id' => $anchorCategory->getId()]);
 }
 }
 }
return $urls;
 }

step2 : module-catalog-url-rewrite/Model/ProductUrlRewriteGenerator.php (Line 146)

/**
     * Generate list of urls for global scope
     *
     * @param \Magento\Framework\Data\Collection $productCategories
     *
     * @return \Magento\UrlRewrite\Service\V1\Data\UrlRewrite[]
     */
     protected function generateForGlobalScope($productCategories)
     {
     $urls = [];
     $productId = $this->product->getEntityId();
     foreach ($this->product->getStoreIds() as $id) {
     if (!$this->isGlobalScope($id)
     && !$this->storeViewService->doesEntityHaveOverriddenUrlKeyForStore($id, $productId, Product::ENTITY)
     ) {
     // Default: $urls = array_merge($urls, $this->generateForSpecificStoreView($id, $productCategories));
     // before loading the category collection by looping it, clone it and set the correct store id,
     // so we get the correct url_path & url_key for that specific store id
     $storeSpecificProductCategories = clone $productCategories;
     $storeSpecificProductCategories->setStoreId($id);
    $urls = array_merge($urls, $this->generateForSpecificStoreView($id, $storeSpecificProductCategories));
     }
     }
     return $urls;
     }
  • please your code i have dont understand because your code in many <br> <p> available – Rakesh Donga Jun 21 at 9:34
  • check now, its code editor issue. – Anas Mansuri Jun 21 at 9:37
  • thanks ok let me check – Rakesh Donga Jun 21 at 9:41
  • not working for me – Rakesh Donga Jun 21 at 9:49
  • than please truncate url_rewrite table, than execute normal command which we are using. – Anas Mansuri Jun 21 at 9:52
0

1 Run the following SQL queries from the command line or phpMyAdmin,

SET FOREIGN_KEY_CHECKS = 0; 
TRUNCATE TABLE url_rewrite; 
SET FOREIGN_KEY_CHECKS = 1;

2 Within your backend, navigate to Products > Catalog.

3.Clear any and all filters, select all products (drop down menu option Select All).

4 Select the Update Attributes action from the Actions dropdown menu.

5 Under Products Information, click the Websites tab.

6 Under the Add Product to Websites section, check the box for Main Website (and any other sites you may have)

7 Click Save.

8 Navigate to Products > Categores.

9 For each category you want to have a new URL key written, select it, update the URL key, ensure that the Create Permanent Redirect for Old URL checkbox is checked.

10 Click Save.

0

There are so may issue is already reported on stack & GitHub and other community. and there are so many solutions for that and which one is correct it is to difficult choosing the right one. but I see one issue is reported on GitHub which one help to you I think. https://github.com/magento/magento2/issues/7298

This issue occurring due to duplicate entry on the database table url_rewrite, so there is only one way to resolve this issue you need to empty the table and regenerate the URL. so I have checked and found one answer which one usefull to me which I shared below.


Note: Take database backup before doing below opration.

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);
}

I found out $data variable has a duplicate record. If you want this method to work without any errors. Rewrite this method above to below one.

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); 
}

Taje refrance from Magento 2 Duplicate Product URLs Problem And "URL key for specified store already exists." cannot save category #7298 I hope it helps!

  • you are right @Chirag patel but default function is like : prntscr.com/o4sibb – Rakesh Donga Jun 21 at 10:12
  • There might be different code in function because of the different Magento version. so you have debugged this code and I have shared logic Remove duplication data; try this – Chirag Patel Jun 21 at 10:16
  • Just print $data variable of your function and check what's going wrong. – Chirag Patel Jun 21 at 10:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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