How to solve the error : “Could not save product “20072” with position 0 to category 7″ in magento 2

The question:

While unasign the product from multiple categories to single category and trying to save the product, it thorow the error like below

Could not save product “20072” with position 0 to category 7

I am saving the product mannually via admin end

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

It is fixed in Magento latest version.

You can check fixes here.

Method 2

To fix this issue i created a custom module.

https://github.com/khasru/magento2UrlRewritebug

Hope it helps.

Method 3

public function deleteByIds($categoryId, $sku)
{
    $category = $this->categoryRepository->get($categoryId);
    $product = $this->productRepository->get($sku);
    $productPositions = $category->getProductsPosition();

    $productID = $product->getId();
    if (!isset($productPositions[$productID])) {
        throw new InputException(__('Category does not contain specified product'));
    }
    $backupPosition = $productPositions[$productID];
    unset($productPositions[$productID]);

    $category->setPostedProducts($productPositions);
    try {
        $category->save();
    } catch (Exception $e) {
        echo $e->getMessage();
        exit;
        throw new CouldNotSaveException(
            __(
                'Could not save product "%product" with position %position to category %category',
                [
                    "product" => $product->getId(),
                    "position" => $backupPosition,
                    "category" => $category->getId()
                ]
            ),
            $e
        );
    }
    return true;
}

the “echo $e->getMessage();” gives you the exact error.
In my case it was “Duplication of URL key.”

So just check what error message you are getting from here….

File: Vendor/magento/module-catalog/Model/CategoryLinkRepository.php


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment