cancel
Showing results for 
Search instead for 
Did you mean: 

Create and link both simple and configurable products programmatically

Create and link both simple and configurable products programmatically

Hi everyone,

 

I'm seriously struggling with this problem. I need to be able to create simple products programmatically, and also its counterpart configurable products. But no matter what I seem to do it just doesn't work.

 

Creating simple products is easy, creating the configurable is easy - but for some reason when I try to associate simple products to the configurable, it just won't take them. Its like its ignoring them. But the worst part is that there are no errors when saving.

 

I've previously posted my examples and problem on here: https://magento.stackexchange.com/q/184145/45073 but so far I still haven't got a viable working code for it. I really need to be able to get this to work!

 

Here's what my code looks like:

 

namespace Company\Module\Controller\Get;

use Magento;
use Company\Module\Helper\Helper;

class OutboundItem extends Magento\Framework\App\Action\Action
{
    protected $storeManager;
    protected $productFactory;
    protected $indexerFactory;
    public $helper;

    public function __construct(
        Magento\Framework\App\Action\Context $context,
        Magento\Store\Model\StoreManagerInterface $storeManager,
        Magento\Catalog\Model\ProductFactory $productFactory,
        Magento\Indexer\Model\IndexerFactory $indexerFactory,
        Helper $helper
    )
    {
        $this->storeManager = $storeManager;
        $this->productFactory = $productFactory;
        $this->indexerFactory = $indexerFactory;
        $this->helper = $helper;
        return parent::__construct($context);
    }

    public function execute()
    {
        // Get Website ID
        $websiteId = $this->storeManager->getWebsite()->getWebsiteId();
        $storeId = $this->storeManager->getDefaultStoreView()->getId();

        // Get the the list of products that need importing from the document.
        $items = $this->helper->getItems();

        // Loop through all the results.
        foreach ($items as $item) {
            try {
                // Create common product info variables.
                $product_name = $item->ProdName;
                $price = $item->UnitPrice;
                $weight = $item->NetWeight;
                $categoryIds = [2, $this->helper->getCategoryIdByName(substr($product_name, 0, 1))];

                // Create variable to store the created variant ids.
                $variant_ids = array();

//                $prodData = array();
                // Loop through the variants.
                foreach ($item->variants as $variant) {
                    $product = $this->productFactory->create();

                    // Preparing data for new customer.
                    $product->setSku($product_name . '_' . $variant->Code);
                    $product->setName($variant->Description); // Name of Product
                    $product->setAttributeSetId($product->getDefaultAttributeSetId()); // Attribute set id
                    $product->setStatus(1); // Status on product enabled/ disabled 1/0
                    $product->setWeight($weight); // weight of product
                    $product->setVisibility(Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE); // visibilty of product (catalog / search / catalog, search / Not visible individually)
                    $product->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
                    $product->setPrice($variant->SalesPrice); // price of product
                    $product->setStockData(
                        array(
                            'use_config_manage_stock' => 0,
                            'manage_stock' => 1,
                            'is_in_stock' => 1,
                            'qty' => $variant->AvailableQuantity
                        )
                    );

                    $product->setWebsiteIds(array($websiteId));
                    $product->setCategoryIds($categoryIds);
                    $product->setStoreId($storeId);

                    $colour = $variant->value2;
                    $colourId = $this->helper->createOrGetId('color', $colour);
                    $product->setColor($colourId);

                    $size = $variant->value1;
                    $sizeId = $this->helper->createOrGetId('size', $size);
                    $product->setSize($sizeId);

                    // Save data.
                    $product->save();

                    if ($product->getId() > 0) {
                        $variant_ids[] = $product->getId();
//                        $prodData[$product->getId()] = array(
//                            '0' => array(
//                                'label' => 'Size',
//                                'attribute_id' => $this->helper->getAttribute('size')->getAttributeId(),
//                                'value_index' => $sizeId
//                            ),
//                            '1' => array(
//                                'label' => 'Color',
//                                'attribute_id' => $this->helper->getAttribute('color')->getAttributeId(),
//                                'value_index' => $colourId
//                            )
//                        );
                    }

                    $prodConfAttr = $product->getExtensionAttributes();
                    $prodConfAttr->setConfigurableProductLinks($variant_ids);
                    $product->setExtensionAttributes($prodConfAttr);
                }

                // Instantiate magento customer object.
                $product = $this->productFactory->create();

                // Preparing data for new customer.
                $product->setTypeId('configurable'); // type of product (simple/virtual/downloadable/configurable)
                $product->setSku($product_name);
                $product->setName($product_name); // Name of Product
                $product->setAttributeSetId($product->getDefaultAttributeSetId()); // Attribute set id
                $product->setStatus(1); // Status on product enabled/ disabled 1/0
                $product->setWeight($weight); // weight of product
                $product->setVisibility(Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH); // visibilty of product (catalog / search / catalog, search / Not visible individually)
                $product->setPrice($price); // price of product
                $product->setStockData(
                    array(
                        'use_config_manage_stock' => 0,
                        'manage_stock' => 1,
                        'is_in_stock' => 1
                    )
                );
                //setCategoryId?
                $product->setWebsiteIds(array($websiteId));
                $product->setCategoryIds($categoryIds);
                $product->setStoreId($storeId);

                // Set variants
//                $product->setNewVariationsAttributeSetId($product->getDefaultAttributeSetId());
//                $product->setAssociatedProductIds($variant_ids);
//                $product->setAffectConfigurableProductAttributes(4);
//
//                $product->getTypeInstance()->setUsedProductAttributeIds(array(
//                    $this->helper->getAttribute('color')->getAttributeId(),
//                    $this->helper->getAttribute('size')->getAttributeId()
//                ), $product);
//                $attData = $product->getTypeInstance()->getConfigurableAttributesAsArray();
//                $product->setCanSaveConfigurableAttributes(true);
//                $product->setConfigurableAttributesData($attData, $product);
////                $prodData = array();
////                foreach($variant_ids as $key => $id) {
////                    $prodData[$id] = array(
////                        '0' => array(
////                            'label'
////                        )
////                    );
////                }
//                $product->setConfigurableProductsData($prodData);

//                unset($variant_ids);

                // Save data.
                $product->save();

                echo $this->helper->getPrint($variant_ids);
                echo $this->helper->getPrint($categoryIds);
                echo $this->helper->getPrint($storeId);
                echo $this->helper->getPrint($item);
            } catch (\Exception $e) {
                echo $this->helper->getPrint($item);
                echo $this->helper->getPrint($e->getMessage());
            }
        }

        echo $this->helper->getPrint('Import Complete.');

        exit;
    }
}
2 REPLIES 2

Re: Create and link both simple and configurable products programmatically

Check this blog, it may solve the problem

 

https://firebearstudio.com/blog/how-to-programmatically-create-a-configurable-magento-2-product.html

Suman Kar(suman.jis@gmail.com) Magento Certified Developer Plus Skype: sumanphptech Problem solved? Please give 'Kudos' and accept 'Answer as Solution'.

Re: Create and link both simple and configurable products programmatically

The given link code is not working.