6

When i save product after unassigned all category from product. I am getting error Could not save product "330664" with position 0 to category 3567

I have checked log and i can see same thing in exception.log. I found that error is coming from 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 same issue?

2
6

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? – jafar pinjar Nov 24 '18 at 11:01
  • In my case it's fixed. – Nitin Vala Nov 26 '18 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 '19 at 11:23
  • @NitinVala how to fix this? – Divyesh Nov 11 '19 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 '19 at 10:42
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
        );
    }
}
1

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.

2
  • your solution is really appreciable bro.... thanks for the solution – Suraj Prajapat Apr 13 at 10:42
  • Happy to hear it work for you :) – Vish V Apr 14 at 11:14
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 – Dominic Xigen Oct 22 '19 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
-3

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 '20 at 19:30
  • This will destroy your SEO – Black Sep 24 '20 at 12:42

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.