0

I am getting an error in a external script when I am trying to save a grouped product : something goes wrong with product save method, the exception is "Requested product doesn't exist".

enter image description here

Doing unit test for one grouped product, get all associated products for this one and then rebuild links. Then save the grouped product.

//START TEST
$productId = 7986;
$associated = array();
$position = 0;
$productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');

$product = $productRepository->getById($productId);
$childrenProducts = $product->getTypeInstance()->getAssociatedProducts($product);

foreach($childrenProducts as $item) {
  $position++;

  $childrenId = $item->getId();
  $linkedProduct = $productRepository->getById($childrenId);

  //@var \Magento\Catalog\Api\Data\ProductLinkInterface $productLink
  $productLink = $objectManager->create(\Magento\Catalog\Api\Data\ProductLinkInterface::class);
  echo $linkedProduct->getSku().'<br />';
  echo $linkedProduct->getTypeId().'<br />';

  $productLink->setLinkType('associated')
    ->setLinkedProductSku($linkedProduct->getSku())
    ->setLinkedProductType($linkedProduct->getTypeId())
    ->setPosition($position)
    ->getExtensionAttributes();

  $associated[] = $productLink;
  $j++;
}

$product->setProductLinks($associated);
$product->save();
$i++;
//END TEST

Started from this script : http://www.w3solver.com/magento-2-add-a-grouped-product-programmatically/#

Please note :

  • The grouped product has an SKU and is active
  • Run reindex and refresh cache didn't change nothing

What's going wrong ?

Magento CE 2.2.2

  • Did you create child product for this group product? – Mayur Oct 16 at 15:57
  • Can you please add try cache in your script when you load product using getById() ? – Kishan Savaliya Oct 16 at 16:03

Your Answer

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

Browse other questions tagged or ask your own question.