Magento, Magento 2

How to Create Bundle Product Programmatically in Magento 2

How to Create Bundle Product Programmatically in Magento 2

In this tutorial, I will explain to how to create bundle product programmatically in Magento 2. The Bundle Product is customizable product that can build your own. Each item in the bundle product can be based on these two product types : simple product and virtual product.

In this you can set dynamic or fixed value for the bundle product. But, if we perform from the admin panel and create the product from the admin panel it takes a little bit a long time. At that time, the script will be helpful for you to create a bundle product quickly.

When we need to create bundle product using script instead of admin panel. Then, how we can create it by script?

You may also like this :

List of article to create product programmatically with different types :

Let’s create the script for that. First of all, create bundleproduct.php file at your Magento’s root folder and add this below code (It’s working code). 

<?php
/**
 * Created By : Rohan Hapani
 */
use Magento\Framework\App\Bootstrap;

require __DIR__ . '/app/bootstrap.php';

$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$product = $objectManager->create('Magento\Catalog\Model\Product');

try {
    $product->setName('Bundle Product'); // Set Product Name
    $product->setTypeId('bundle'); // Set Product Type Id
    $product->setAttributeSetId(11); // Set Attribute Set ID
    $product->setSku('bundle-product'); // Set SKU
    $product->setWebsiteIds([1]); // Set Website Ids
    $product->setVisibility(4); // Set Visibility
    $product->setImage('/bundle/test.jpg'); // Image Path
    $product->setSmallImage('/bundle/test.jpg'); // Small Image Path
    $product->setThumbnail('/bundle/test.jpg'); // Thumbnail Image Path
    $product->setPriceType(0);
    $product->setPriceView(0);
    $product->save();
    $product = $objectManager->create('Magento\Catalog\Model\Product')->load($product->getId());
    // Set bundle product items
    $product->setBundleOptionsData(
        [
            [
                'title' => 'Bundle Product Items 1',
                'default_title' => 'Bundle Product Items 1',
                'type' => 'select',
                'required' => 1,
                'delete' => '',
            ],
            [
                'title' => 'Bundle Product Items 2',
                'default_title' => 'Bundle Product Items 2',
                'type' => 'select',
                'required' => 1,
                'delete' => '',
            ]
        ]
    )->setBundleSelectionsData(
        [
            [
                ['product_id' => 1, 'selection_qty' => 1, 'selection_can_change_qty' => 1, 'delete' => ''],
                ['product_id' => 3, 'selection_qty' => 1, 'selection_can_change_qty' => 1, 'delete' => ''],
            ],
            [
                ['product_id' => 2, 'selection_qty' => 1, 'selection_can_change_qty' => 1, 'delete' => ''],
                ['product_id' => 4, 'selection_qty' => 1, 'selection_can_change_qty' => 1, 'delete' => ''],
            ],
        ]
    );
    if ($product->getBundleOptionsData())
    {
        $options = [];
        foreach ($product->getBundleOptionsData() as $key => $optionData)
        {
            if (!(bool) $optionData['delete'])
            {
                $option = $objectManager->create('Magento\Bundle\Api\Data\OptionInterface');
                $option->setData($optionData);
                $option->setSku($product->getSku());
                $option->setOptionId(null);

                $links = [];
                $bundleLinks = $product->getBundleSelectionsData();
                if (!empty($bundleLinks[$key]))
                {
                    foreach ($bundleLinks[$key] as $linkData)
                    {
                        if (!(bool) $linkData['delete'])
                        {
                            /** @var \Magento\Bundle\Api\Data\LinkInterface$link */
                            $link = $objectManager->create('Magento\Bundle\Api\Data\LinkInterface');
                            $link->setData($linkData);
                            $linkProduct = $objectManager->get('\Magento\Catalog\Api\ProductRepositoryInterface')->getById($linkData['product_id']);
                            $link->setSku($linkProduct->getSku());
                            $link->setQty($linkData['selection_qty']);
                            if (isset($linkData['selection_can_change_qty']))
                            {
                                $link->setCanChangeQuantity($linkData['selection_can_change_qty']);
                            }
                            $links[] = $link;
                        }
                    }
                    $option->setProductLinks($links);
                    $options[] = $option;
                }
            }
        }
        $extension = $product->getExtensionAttributes();
        $extension->setBundleProductOptions($options);
        $product->setExtensionAttributes($extension);
    }
    $product->save();
    if ($product->getId())
    {
        echo "Product Created Successfully";
    }
} catch (\Exception $e) {
    echo $e->getMessage();
}

That’s it !!

In addition, You can set static details based on your requirements. If you want to create multiple products programmatically by the script at that time, you can use this script and customize code for multiple products create.

Now, execute this file at frontend side : {baseUrl}/bundleproduct.php

I hope this blog will helpful for easily understand how to create a bundle product programmatically in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Keep liking and sharing 🙂

 

 

Tagged ,