0

I am trying to update a configurable product SKU and it is children SKU in observer after this event catalog_product_save_after. When I update the SKU the association between parent and child product are broken.

public function execute(Observer $observer)
{
    $_product = $observer->getProduct();

    if ($_product->getTypeId() === 'configurable' && strpos($_product->getSku(), 'auto') !== false) {
        $parentProduct = $this->productRepository->getById($_product->getId());
        $childrenIds = array();
        $children = $parentProduct->getTypeInstance()->getUsedProducts($parentProduct);

        foreach ($children as $child) {
            $childrenIds[] = $child->getId();
            $child->setSku('any-new-sku');
            $child->save();
        }
        $parentProduct->setSku('any-new-sku');
        $parentProduct->setAssociatedProductIds($childrenIds);
        $parentProduct->save();
    }
}

so basically, I am getting the product from the observer. And if the product is configurable and the SKU have 'auto' keyword. I will get all children and update the childrens' and parent SKU's. But using this code the association between parent and children are gone.

How can I solve this issue ?

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.