Skip to content

Duplicate configurable and childs products are not properly created

For a given feature I need to duplicate with very small modification existing configurable and childs products. This is what is doing this method.

The products configurable and ‘subscription’ childs, are created, but there are 2 issues remaining.

1 – It seems that the images are not properly added to the new products

2 – The link of the new configurable and the new childs of this configurable is not done; resulting in products being created but the configuration of color is not existing.

Here is the full code of the method. Thanks for assist

public function createSubscriptionMachineProduct(){
    $machines = $this->productCollectionFactory->create()
        ->addFieldToSelect('sku')
        ->addFieldToFilter('type_id', 'configurable')
        ->addFieldToFilter('status', Status::STATUS_ENABLED)
        ->addFieldToFilter('attribute_set_id', self::MACHINE_ATTRIBUTE_SET_ID);

    foreach ($machines as $machine){
        try {
            $originalConfigurableProduct = $this->productRepository->get($machine->getSku());
            $name = $originalConfigurableProduct->getName();
            $originalParentImages = $originalConfigurableProduct->getMediaGalleryImages();

            $subscriptionSku = 'subscription-' . $originalConfigurableProduct->getSku();

            try {
                $subscriptionConfigurableProduct = $this->productFactory->create();
                $subscriptionConfigurableProduct->setSku($subscriptionSku);
                $subscriptionConfigurableProduct->setUrlKey($subscriptionSku);
                $subscriptionConfigurableProduct->setAttributeSetId($originalConfigurableProduct->getAttributeSetId());
                $subscriptionConfigurableProduct->setName($name);
                $subscriptionConfigurableProduct->setTypeId('configurable');
                $subscriptionConfigurableProduct->setStatus(Status::STATUS_ENABLED);
                $this->productRepository->save($subscriptionConfigurableProduct);
                $this->logger->logSuccess("Parent sub saved: " . $subscriptionSku);

                try {
                    foreach ($originalParentImages as $image) {
                        $path = $image->getPath();
                        $subscriptionConfigurableProduct->addImageToMediaGallery($path, ['image', 'thumbnail', 'small_image', 'base'], false, false);
                    }
                    $this->productRepository->save($subscriptionConfigurableProduct);
                } catch (Exception $exception) {
                    $this->logger->logError($exception->getMessage());
                }

                $subscriptionAttributeSetId = $this->getSubscriptionAttributeSetId();
                $associatedProductIds = [];
                $configurableAttributesData = [];

                $configurableProductType = $this->configurableTypeFactory->create();
                $childrenIds = $configurableProductType->getChildrenIds($originalConfigurableProduct->getId());

                foreach ($childrenIds as $childIds) {
                    foreach ($childIds as $childProductId) {
                        $originalChildProduct = $this->productRepository->getById($childProductId);
                        $childSku = 'subscription-' . $originalChildProduct->getSku();
                        $originalImages = $originalChildProduct->getMediaGalleryImages();

                        $subscriptionChildProduct = $this->productFactory->create();
                        $subscriptionChildProduct->setSku($childSku);
                        $subscriptionChildProduct->setUrlKey($childSku);
                        $subscriptionChildProduct->setName($originalChildProduct->getName());
                        $subscriptionChildProduct->setPrice($originalChildProduct->getPrice());
                        $subscriptionChildProduct->setAttributeSetId($subscriptionAttributeSetId);
                        $subscriptionChildProduct->setVisibility(MagentoCatalogModelProductVisibility::VISIBILITY_NOT_VISIBLE);
                        $subscriptionChildProduct->setStatus(MagentoCatalogModelProductAttributeSourceStatus::STATUS_ENABLED);
                        $subscriptionChildProduct->setWebsiteIds($originalChildProduct->getWebsiteIds());
                        $subscriptionChildProduct->setSubscriptionType('abo-machine');
                        $subscriptionChildProduct->setSubscriptionPrice(19);
                        $subscriptionChildProduct->setSubscriptionInitialProduct($originalChildProduct->getSku());
                        $subscriptionChildProduct->setSubscriptionTime(12);
                        $subscriptionChildProduct->setSubscriptionConsomation('one_per_day');

                        $this->productRepository->save($subscriptionChildProduct);
                        $this->logger->logSuccess("Child Sub saved: " . $childSku);

                        try {
                            foreach ($originalImages as $image) {
                                $path = $image->getPath();
                                $subscriptionChildProduct->addImageToMediaGallery($path, ['image', 'thumbnail', 'small_image', 'base'], false, false);
                            }
                            $this->productRepository->save($subscriptionChildProduct);
                        } catch (Exception $exception) {
                            $this->logger->logError($exception->getMessage());
                        }

                        $associatedProductIds[] = $subscriptionChildProduct->getId();

                        // Ajouter les informations de l'attribut configurable (couleur)
                        $colorValue = $originalChildProduct->getData('color');
                        $configurableAttributesData[] = [
                            'attribute_id' => $this->eavConfig->getAttribute('catalog_product', 'color')->getAttributeId(),
                            'value_index' => $colorValue
                        ];
                    }
                }

                // Associer les produits enfants et définir les options configurables
                $configurableOptions = [];
                foreach ($configurableAttributesData as $configurableAttribute) {
                    $option = $this->optionInterfaceFactory->create();
                    $option->setAttributeId($configurableAttribute['attribute_id']);
                    $option->setValues([$configurableAttribute['value_index']]);
                    $configurableOptions[] = $option;
                }

                $extensionAttributes = $subscriptionConfigurableProduct->getExtensionAttributes();
                $extensionAttributes->setConfigurableProductLinks($associatedProductIds);
                $extensionAttributes->setConfigurableProductOptions($configurableOptions);

                $subscriptionConfigurableProduct->setExtensionAttributes($extensionAttributes);

                $this->productRepository->save($subscriptionConfigurableProduct);
                $this->logger->logSuccess("Link saved!");
            } catch (Exception $exception) {
                $this->logger->logError($exception->getMessage());
            }
        } catch (NoSuchEntityException $e) {
            $this->logger->logError($e->getMessage());
        }
    }
}

Log result looks like

2024-10-03T15:49:08+00:00 INFO (6): [SUCCESS] Parent sub saved: subscription-Lattissima One
2024-10-03T15:49:08+00:00 ERR (3): [FAILURE] The image doesn't exist.
2024-10-03T15:49:10+00:00 INFO (6): [SUCCESS] Child Sub saved: subscription-F121-EU-WH-NE-1
2024-10-03T15:49:10+00:00 ERR (3): [FAILURE] The image doesn't exist.
2024-10-03T15:49:11+00:00 INFO (6): [SUCCESS] Child Sub saved: subscription-F121-EU-BK-NE-1
2024-10-03T15:49:11+00:00 ERR (3): [FAILURE] The image doesn't exist.
2024-10-03T15:49:11+00:00 ERR (3): [FAILURE] The product that was requested doesn't exist. Verify the product and try again.