Import Grouped Products Magento 2

This tutorial explains how to import grouped products Magento 2.

Step by step explanation

  • Import Simple Products
  • Import Grouped Products
  • Assign simple product to parent product

Import Grouped Products Magento 2

Import Simple Products

As the first step import the simple products associated with the grouped product and set the visibility disable and set the type id simple.

Import Grouped Products Magento 2

Next step import the parent product and set type id grouped.

Link associated products

Next step assign the associated products to the parent product.

Import Grouped Products Magento 2

Please also refer the other tutorials which explain how to import grouped products in magento 1.

Import Simple Products

function importSimpleProducts( $importProducts, $objectManager, $storeId, $dir, $listCategoryId ) {

    $stockSt = 1;
    $simpleProductsArray = $allData =  $parentProdArray = $urlArr = array();
    $i = 0;

    foreach( $importProducts as $importProduct ) {

        try {
                $product = $objectManager->create('\Magento\Catalog\Model\Product');
                $product->setCreatedAt(strtotime('now'));
                $product->setName(trim($importProduct[0]));
                $product->setSku(trim($importProduct[6]));
                $product->setWebsiteIds(array(1));
                $product->setAttributeSetId(4);
                $product->setTypeId('simple');
                $product->setWeight(1);
                $product->setStatus(0);
                $product->setUrlKey(str_replace(' ', '-', strtolower(trim($importProduct[0]))));
                if (strtolower(trim($importProduct[8])) == 'instock') {
                    $stockSt = 1;
                } else {
                    $stockSt = 0;
                }    
                $category_id = newCategoryIds(trim($importProduct[12]), $listCategoryId);
                $product->setCategoryIds($category_id);
                $product->setTaxClassId(2); // (0 - none, 1 - default, 2 - taxable, 4 - shipping)               
                $product->setVisibility(1); // catalog and search visibility               
                $product->setPrice(trim($importProduct[9]));
                $product->setMetaTitle($importProduct[0]);
                $product->setMetaKeyword('Meta Keyword');
                $product->setMetaDescription('Default Meta Description');
                $product->setDescription(!empty($importProduct[13]) ? strip_tags($importProduct[13]) : 'Long Description');
                $product->setShortDescription(!empty($importProduct[3]) ? strip_tags($importProduct[3]) : 'Short Description');
                $product->setStockData(
                    array(
                        'use_config_manage_stock' => 0,
                        'manage_stock' => 1, // manage stock
                        'is_in_stock' => $stockSt, // Stock Availability of product
                        'qty' => 100
                    )
                );
                $product = addImages($importProduct, $product, $dir);
                if ($product->save()) {
                    echo "Upload simple product id : " . $importProduct[0] . ' ' . $product->getId() . PHP_EOL;
                    echo "-----------------------------------------------------------------------------------".PHP_EOL;

                }
                $simpleProductsArray[$importProduct[2]] = $product->getId();
                /* Save the childern product id for assign that to the parent products*/
                $parentProdArray[trim($importProduct[5])][] = $product->getId();
                $allData[$importProduct[2]] = array($importProduct[2],$product->getId());            
        }
        catch(Exception $e)
        {
            echo 'Something failed for product import ' . $importProduct[0] . PHP_EOL;
            print_r($e->getMessage());
        }
    }
    importGroupedProducts( $importProducts, $objectManager, $storeId, $dir, $listCategoryId,$simpleProductsArray,$parentProdArray,$allData,$urlArr,$i );
}

Import Grouped Products

function importGroupedProducts( $importProducts, $objectManager, $storeId, $dir, $listCategoryId,$simpleProductsArray,$parentProdArray,$allData,$urlArr,$i ) {

    $stockSt = 1;
    foreach( $importProducts as $importProduct ) {
        try {
            if(strtolower(trim($importProduct[11])) == 'grouped') {
                $product = $objectManager->create('\Magento\Catalog\Model\Product');
                $product->setWebsiteIds(array(1));
                $product->setAttributeSetId(4);
                $product->setTypeId('grouped');
                $product->setCreatedAt(strtotime('now'));
                $product->setName(trim($importProduct[0]));
                $product->setSku(trim($importProduct[6]));                
                $product->setWeight(1);
                $product->setStatus(1);               
                $product->setUrlKey(trim(str_replace(' ', '-', strtolower(trim($importProduct[0])))));
                $category_id = newCategoryIds(trim($importProduct[12]), $listCategoryId);
                $product->setCategoryIds($category_id);
                $product->setTaxClassId(2); // (0 - none, 1 - default, 2 - taxable, 4 - shipping)
                $product->setVisibility(4); // catalog and search visibility                
                $product->setPrice(trim($importProduct[9]));
                $product->setMetaTitle($importProduct[0]);
                $product->setMetaKeyword('Meta Keyword');
                $product->setMetaDescription('Default Meta Description');
                $product->setDescription(!empty($importProduct[13]) ? strip_tags($importProduct[13]) : 'Long Description');
                $product->setShortDescription(!empty($importProduct[3]) ? strip_tags($importProduct[3]) : 'Short Description');

                $product->setStockData(
                    array(
                        'use_config_manage_stock' => 0,
                        'manage_stock' => 1, // manage stock
                        'is_in_stock' => $stockSt, // Stock Availability of product
                        'qty' => 100
                    )
                );

                if ($product->save()) {
                    echo "Upload grouped product id : " . $importProduct[0] . ' ' . $product->getId() . PHP_EOL;
                    echo "-----------------------------------------------------------------------------------".PHP_EOL;
                }
                $simpleProductsArray[$importProduct[2]] = $product->getId();
                $parentProdArray[trim($importProduct[5])][] = $product->getId();
                groupedProducts($objectManager,$product,$parentProdArray,$importProduct);
                $allData[$importProduct[2]] = array($importProduct[2],$product->getId());

            }
        }
        catch(Exception $e)
        {
            echo 'Something failed for product import ' . $importProduct[0] . PHP_EOL;
            echo 'Error : '.$e->getMessage().PHP_EOL;
        }
    }

}

Assign simple product to parent product

function groupedProducts($objectManager,$product,$parentProdArray,$importProduct) {

    $childrenIds = array();

    if(!isset($parentProdArray[$importProduct[2]])) {

        echo 'Product Id with grouped product not existing '.$importProduct[2].' : '.$product->getId().PHP_EOL;
        return;

    }
    /* $parentProdArray contains children product ids*/
    foreach ($parentProdArray[$importProduct[2]] as $key=>$value) {

        $childrenIds[] = $value;
    }

    $associated = array();
    $position = 0;

    foreach($childrenIds as $productId) {
        $position++;
        $productRepository = $objectManager->create('\Magento\Catalog\Api\ProductRepositoryInterface');
        $linkedProduct = $productRepository->getById($productId);
        $productLink = $objectManager->create('Magento\Catalog\Api\Data\ProductLinkInterface');
        $productLink->setSku($product->getSku())
            ->setLinkType('associated')
            ->setLinkedProductSku($linkedProduct->getSku())
            ->setLinkedProductType($linkedProduct->getTypeId())
            ->setPosition($position)
            ->getExtensionAttributes()
            ->setQty(0);
        $associated[] = $productLink;     
    }
    $product->setProductLinks($associated);
    $product->save();

}

Share this Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

*