Creating Grouped Product Programmatically in Magento 2

A grouped product is a collection of simple standalone products that are presented as a group based on season, colour or theme. Presenting a grouped item on the same page can easily motivate customers to purchase multiple items at once. For example, you can show the dress with accessories like sneakers, sunglasses, etc on a single page.

Each product in the group can be purchased as a separate item, or all together as part of the group. In the shopping cart, each of the items and the quantity purchased will appear as a separate line item.

In Magento 2 admin panel, you can create any number of products. But if you need to create a grouped product with an external script, this article will help you.

Initialize Object Manager And Set Area Code

While creating an external script, first you have to include the below code in the top of the file,

use Magento\Framework\App\Bootstrap;
  
/**
 * If the external file is in the root folder
 */
require __DIR__ . '/app/bootstrap.php';
  
$params = $_SERVER;
  
$bootstrap = Bootstrap::create(BP, $params);

The purpose of the above code is used to access the Magento 2 core functionality from your external file.

Moving on, use the below script to set the area code as adminhtml,

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML);

Create Grouped Product

Use the below code to create the grouped product programmatically.

As you may know that in order to create new product in Magento 2, it’s necessary to use the \Magento\Catalog\Api\Data\ProductInterfaceFactory & \Magento\Catalog\Api\ProductRepositoryInterface classes in your custom script.

$productInterfaceFactory = $objectManager->create('Magento\Catalog\Api\Data\ProductInterfaceFactory');
$productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');

$product = $productInterfaceFactory->create();

// Get the default attribute set id
$attributeSetId = $product->getDefaultAttributeSetId();

$sku = $urlKey = 'test-grouped-product';
$product->setSku($sku)
        ->setName('Test Grouped Product')
        ->setUrlKey($urlKey)
        ->setAttributeSetId($attributeSetId)
        ->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
        ->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
        ->setTypeId(\Magento\GroupedProduct\Model\Product\Type\Grouped::TYPE_CODE)
        ->setWebsiteIds([1]) // Assign product to websites
        ->setCategoryIds([11, 12, 13]) // Assign product to categories using category id
        ->setPrice(100)
        ->setStockData(
            [
                'use_config_manage_stock' => 1,
                'is_in_stock' => 1
            ]
        );

$product = $productRepository->save($product);
if ($product->getId()) {
    echo "Product Created Successfully";
}

Associate Child Products To Grouped Product

Use the below code to assign the child products to the grouped product. To add the child products to the grouped product, you need to use the \Magento\Catalog\Api\Data\ProductLinkInterface class in your script.

$childIds = [1, 2, 3]; // Set associated product ids
$associated = [];
$position = 0;
foreach ($childIds as $productId) {
    $position++;
    $linkedProduct = $objectManager->create('\Magento\Catalog\Api\ProductRepositoryInterface')->getById($productId);
    $productLink = $objectManager->create('\Magento\Catalog\Api\Data\ProductLinkInterface');
    $productLink->setSku($product->getSku())
            ->setLinkType('associated') // Set link type
            ->setLinkedProductSku($linkedProduct->getSku()) // Set link product SKU
            ->setLinkedProductType($linkedProduct->getTypeId()) // Set link product type
            ->setPosition($position) // Set position
            ->getExtensionAttributes()
            ->setQty(1); // Set associated product default QTY
    $associated[] = $productLink;
}

$product->setProductLinks($associated);
$product->save();

Add Images To Product

Then, use the code below which is used to add the images to the product, Before running this script, the images should be placed in the pub/media/import/ folder.

$filesystem = $objectManager->create('\Magento\Framework\Filesystem');
$mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
$mediaPath = $mediaDirectory->getAbsolutePath();
$imagePath = $mediaPath .'import/sample.jpg'; // Path of the image
$product->addImageToMediaGallery($imagePath, ['image', 'small_image', 'thumbnail'], false, false);
$product->save();

Here is the complete code to create a grouped product in Magento 2 programmatically and assign the child products to it,

<?php
use Magento\Framework\App\Bootstrap;
 
/**
 * If the external file is in the root folder
 */
require __DIR__ . '/app/bootstrap.php';
 
$params = $_SERVER;
 
$bootstrap = Bootstrap::create(BP, $params);
 
$objectManager = $bootstrap->getObjectManager();
 
// Set area code
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML); // or \Magento\Framework\App\Area::AREA_FRONTEND, depending on your need

try {
    $productInterfaceFactory = $objectManager->create('Magento\Catalog\Api\Data\ProductInterfaceFactory');
    $productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');

    $product = $productInterfaceFactory->create();

    // Get the default attribute set id
    $attributeSetId = $product->getDefaultAttributeSetId();

    $sku = $urlKey = 'test-grouped-product';
    $product->setSku($sku)
            ->setName('Test Grouped Product')
            ->setUrlKey($urlKey)
            ->setAttributeSetId($attributeSetId)
            ->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
            ->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
            ->setTypeId(\Magento\GroupedProduct\Model\Product\Type\Grouped::TYPE_CODE)
            ->setWebsiteIds([1]) // Assign product to websites
            ->setCategoryIds([11, 12, 13]) // Assign product to categories using category id
            ->setPrice(100)
            ->setStockData(
                [
                    'use_config_manage_stock' => 1, 
                    'is_in_stock' => 1
                ]
            );

    $product = $productRepository->save($product);

    if ($product->getId()) {
        echo "Product Created Successfully";
    }

    $childIds = [1, 2, 3]; // Set associated product ids
    $associated = [];
    $position = 0;
    foreach ($childIds as $productId) {        
        $position++;
        $linkedProduct = $objectManager->create('\Magento\Catalog\Api\ProductRepositoryInterface')->getById($productId);
        $productLink = $objectManager->create('\Magento\Catalog\Api\Data\ProductLinkInterface');
        $productLink->setSku($product->getSku())
            ->setLinkType('associated') // Set link type
            ->setLinkedProductSku($linkedProduct->getSku()) // Set link product SKU
            ->setLinkedProductType($linkedProduct->getTypeId()) // Set link product type
            ->setPosition($position) // Set position
            ->getExtensionAttributes()
            ->setQty(1); // Set associated product default QTY
        $associated[] = $productLink;
    }
    $product->setProductLinks($associated);
    $product->save();

    $filesystem = $objectManager->create('\Magento\Framework\Filesystem');
    $mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
    $mediaPath = $mediaDirectory->getAbsolutePath();
    $imagePath = $mediaPath .'import/sample.jpg'; // Path of the image
    $product->addImageToMediaGallery($imagePath, ['image', 'small_image', 'thumbnail'], false, false);
    $product->save();

} catch (\Exception $e) {
    echo $e->getMessage();
}

You may also like:

Hope this helps.

Leave a Reply

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