7

When I save a product after unassigning all categories from the product. I am getting the error Could not save product "330664" with position 0 to category 3567

I have checked the log and I can see the same thing in exception.log. I found that the error is coming from the below function from

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

 /**
     * {@inheritdoc}
     */
    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) {
            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;
    }

But not able to find actual cause to throw it. does anyone face the same issue?

3
  • 1
    I think this is the same issue here github.com/magento/magento2/issues/8970
    – Greg Kerr
    Feb 23, 2018 at 8:24
  • @kul any solution for that? Mar 20, 2021 at 20:20
  • This issue may occur with a duplicate product. I solved this issue using the follwing way. Set product "Visibility" to "Not Visible Individually" and then remove the category and save it. After the category is removed and the product is saved, you can set the "Visibility" back to its original value. I hope it will help others. Yes it did, thanks ...
    – Vanlathem
    May 12, 2022 at 8:11

7 Answers 7

9

I faced the same issue and you can find the exact issue by printing actual error from exception.

Temporary replace "deleteByIds" function with following code.

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

After changing this, actual error will print and you will get idea what's the exact problem is.

7
  • hi, Nitin, is this the fix? Nov 24, 2018 at 11:01
  • In my case it's fixed.
    – Nitin Vala
    Nov 26, 2018 at 12:48
  • In My case it gives error: Notice: Undefined index: category_id in /var/www/html/vendor/magento/module-catalog-url-rewrite/Model/Category/Plugin/Storage.php on line 52
    – akgola
    Feb 11, 2019 at 11:23
  • @NitinVala how to fix this?
    – Divyesh
    Nov 11, 2019 at 11:01
  • @Divyesh, Magento by default throwing the exception which not providing the real error information.So, You temporarily need to change the code as I explained above to get the real error.
    – Nitin Vala
    Nov 13, 2019 at 10:42
7

This issue may occur with a duplicate product.

I solved this issue using the following way.

Set product "Visibility" to "Not Visible Individually" and then remove the category and save it. After the category is removed and the product is saved, you can set the "Visibility" back to its original value.

I hope it will help others.

4
  • your solution is really appreciable bro.... thanks for the solution Apr 13, 2021 at 10:42
  • Happy to hear it work for you :) Apr 14, 2021 at 11:14
  • Thanks bro! Saved me lots of time Jul 19, 2021 at 15:22
  • Welcome @JoshuaBarnes You can make it as useful if it works for you. Jul 21, 2021 at 5:13
3

I have same issue and its working with that, In my case its solved when i was set no from admin configuration under Google api "Enable Content Experiments"

Configuration => Sales => Google API => Enable Content Experiments set no and save.

1

In my case I put the erorr message within the returned string

vendor/magento/module-catalog/Model/CategoryLinkRepository.php

public function save(\Magento\Catalog\Api\Data\CategoryProductLinkInterface $productLink)
{
    $category = $this->categoryRepository->get($productLink->getCategoryId());
    $product = $this->productRepository->get($productLink->getSku());
    $productPositions = $category->getProductsPosition();
    $productPositions[$product->getId()] = $productLink->getPosition();
    $category->setPostedProducts($productPositions);
    try {
        $category->save();
    } catch (\Exception $e) {
        throw new CouldNotSaveException(
            __(
                'Could not save product "%1" with position %2 to category %3 : error %4',
                $product->getId(),
                $productLink->getPosition(),
                $category->getId(),
                $e->getMessage()
            ),
            $e
        );
    }
    return true;
}
    /**
     * {@inheritdoc}
     */
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(__("The category doesn't contain the specified product."));
    }
    $backupPosition = $productPositions[$productID];
    unset($productPositions[$productID]);

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

The error was about unique integrity in the database.

And sure enough there were duplicate category IDs in an array I was providing for linking products to categories

public function __construct(
    \Magento\Catalog\Api\CategoryLinkManagementInterface $categoryLinkManagementInterface
) {
    $this->categoryLinkManagementInterface = $categoryLinkManagementInterface;
}

/**
 * Assign product to category
 * @param \Magento\Catalog\Model\Product $product
 * @param array $categoryIds
 * @return void
 */
public function assignProductToCategory($product, $categoryIds = [])
{
    if(!empty($categoryIds)) {
        $this->categoryLinkManagementInterface->assignProductToCategories(
            $product->getSku(),
            $categoryIds
        );
    }
}
0

This error can also be related to trying to assign the product to the same category within the same command.

Say you have an array of Category ID's as follows:

$array = array(1,2,3,4,1);    
$linkManagement = $objectManager->get('\Magento\Catalog\Api\CategoryLinkManagementInterface');
$linkManagement->assignProductToCategories(
                                $product['sku']),
                                $array 
                            );

This would give you the error once it tries to assign the second request for category 1.

1
  • This is a repeat of the issue I highlighted in my answer Oct 22, 2019 at 19:25
-1
If product has duplicated Url: 
Edit product -> Search Engine Optimization -> URL Key -> [OTHER URL] with 'Create Permanent Redirect for old URL' unchecked -> Save
If Mysql has gone away(edit my.ini):
max_allowed_packet = 4000M
-4

100% solution Working:

Delete all Product Url in mysql:

delete from url_rewrite where entity_type = 'product';

Regenerate this url : https://github.com/olegkoval/magento2-regenerate_url_rewrites

2
  • This is not a good approach because if there are custom rewrites it will also permanently delete those as well. Can cause many unexpected consequences.
    – Cypher909
    Jun 9, 2020 at 19:30
  • This will destroy your SEO
    – Black
    Sep 24, 2020 at 12:42

Your Answer

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

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