0

I am new to Magento tried several solutions but I could not create orders with 'Bundle Product' by specifying selection options. Even though if it is an API solution, it may be helpful for me, I will modify it as needed.

  • So did you find any solution? – GunJan Mehta Mar 18 at 10:11
0

Please try with below code :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();     
$productRepository = $objectManager->create(Magento\Catalog\Api\ProductRepositoryInterface::class);

//handle sub-items or sizes
foreach($item->Size as $size){
    //$item_name = $name."-".$size->SizeLabel;
    $sku = strtolower($size->SizeLabel) . "_" . $pID;

    $product = $objectManager->create(\Magento\Catalog\Api\Data\ProductInterface::class);

    $product->setSku($sku);
    $product->setName($size->SizeLabel); // Name of Product
    $product->setAttributeSetId(4);
    $product->setStatus(1);
    $product->setWeight($size->Weight);
    $product->setVisibility(1); 
    $product->setCustomAttribute('tax_class_id', 0);
    $product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE); // type of product (simple/virtual/downloadable/configurable)
    $product->setPrice($size->UnitPrice); // price of product


    /** @var \Magento\CatalogInventory\Api\Data\StockItemInterface $stockItem */
    $stockItem = $objectManager->create(\Magento\CatalogInventory\Api\Data\StockItemInterface::class);
    $stockItem->setUseConfigManageStock(false);
    $stockItem->setManageStock(true);
    $stockItem->getIsInStock(true);
    $stockItem->setQty(9999);
    $productExtension->setStockItem($stockItem);

    /** @var \Magento\Catalog\Api\Data\ProductExtensionInterface $productExtension */
    $productExtension = $objectManager->create(\Magento\Catalog\Api\Data\ProductExtensionInterface::class);

    $product->setExtensionAttributes($productExtension);
    $product = $productRepository->save($product, true);



    /** @var \Magento\Bundle\Api\Data\LinkInterface $link */
    $link = $objectManager->create(\Magento\Bundle\Api\Data\LinkInterface::class);
    $link->setPosition(0);
    $link->setSku($product->getSku());
    $link->setIsDefault(false);
    $link->getQty(1);
    $link->setPrice($size->UnitPrice);
    $link->setPriceType(\Magento\Bundle\Api\Data\LinkInterface::PRICE_TYPE_FIXED);

    $links[] = $link;
}

/** @var \Magento\Catalog\Api\Data\ProductInterface $product */
$product = $objectManager->create(\Magento\Catalog\Api\Data\ProductInterface::class);

$product->setSku('sku'); // Set your sku here
//Map product with category
//$category = $this->_saveCategory($item->WebCategory);
//if ($category->getId())
//{
//    $product->setCategoryIds([$category->getId()]);
//}

$product->setName($name); // Name of Product
$product->setAttributeSetId(4);
$product->setStatus(1); // Status on product enabled/ disabled 1/0
$product->setWeight($item->Weight); // weight of product
$product->setVisibility(4); // visibilty of product (catalog / search / catalog, search / Not visible individually)
$product->setCustomAttribute('tax_class_id', 0);; // Tax class id
$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_BUNDLE); // type of product (simple/virtual/downloadable/configurable)
$product->setPrice($item->UnitPrice); // price of product
$product->setCustomAttribute('description', $item->WebDescription); // description of product

$productExtension = $objectManager->create(\Magento\Catalog\Api\Data\ProductExtensionInterface::class);


/** @var \Magento\Bundle\Api\Data\OptionInterface $option */
$option = $objectManager->create(\Magento\Bundle\Api\Data\OptionInterface::class);
$option->setTitle('Size');
$option->setType('radio');
$option->setRequired(true);
$option->setPosition(1);
$option->setProductLinks($links);
$productExtension->setBundleOptions([$option]);

/** @var \Magento\CatalogInventory\Api\Data\StockItemInterface $stockItem */
$stockItem = $objectManager->create(\Magento\CatalogInventory\Api\Data\StockItemInterface::class);
$stockItem->setUseConfigManageStock(false);
$stockItem->setManageStock(true);
$stockItem->getIsInStock(true);
$stockItem->setQty(9999);
$productExtension->setStockItem($stockItem);

$product->setExtensionAttributes($productExtension);
$productRepository->save($product, true);

hope its work for you

| improve this answer | |
  • Hi, @Anas Mansuri i am asking to create order, not to create product. – user82154 Aug 30 '19 at 9:57
  • The code you provided is for creating product, instead we would like to have code for creating order of a bundle product – GunJan Mehta Mar 18 at 10:08
0

You can try with the below code to create the Bundle products order programmatically in Magento 2

Use the following data to create quote and order

<?php

$options = ['92'=>'49','144'=>'21'];
$order = [
'currency_id' => 'USD',
'email' => 'hello@example.com',
'shipping_address' => [
    'firstname' => 'John',
    'lastname' => 'Doe',
    'street' => 'xxxxxx',
    'city' => 'xxxxxxx',
    'country_id' => 'US',
    'region' => 'xxxxx',
    'postcode' => '85001',
    'telephone' => '52556542',
    'fax' => '3242322556',
    'save_in_address_book' => 1],
    'items' => [
        ['product_id' => '1', 'qty' => 1, 'options' => $options],
        ['product_id' => '2', 'qty' => 2, 'options' => $options]
    ]
];

The order create function in module helper file

<?php
namespace Vendor\Module\Helper;

use Magento\Framework\App\Helper\AbstractHelper;

class Data extends AbstractHelper
{
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Catalog\Model\Product $product,
        \Magento\Framework\Data\Form\FormKey $formkey,
        \Magento\Quote\Model\QuoteFactory $quote, 
        \Magento\Quote\Model\QuoteManagement $quoteManagement,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
        \Magento\Sales\Model\Service\OrderService $orderService) 
    {
        $this->storeManager = $storeManager;
        $this->product = $product;
        $this->formkey = $formkey;
        $this->quote = $quote;
        $this->quoteManagement = $quoteManagement;
        $this->customerFactory = $customerFactory;
        $this->customerRepository = $customerRepository;
        $this->orderService = $orderService;
        parent::__construct($context);
    }

    public function createOrder($order)
    {
        $store = $this->storeManager->getStore();
        $websiteId = $this->storeManager->getStore()->getWebsiteId();
        $customer = $this->customerFactory->create();
        $customer->setWebsiteId($websiteId);
        $customer->loadByEmail($order['email']); // load customet by email address
        if (!$customer->getEntityId()) {
            //If not avilable then create this customer
           $customer->setWebsiteId($websiteId)->setStore($store)->setFirstname($order['shipping_address']['firstname'])->setLastname($order['shipping_address']['lastname'])->setEmail($order['email'])->setPassword($order['email']);
            $customer->save();
        }
        $quote = $this->quote->create(); // Create Quote Object
        $quote->setStore($store); // Set Store
        $customer = $this->customerRepository->getById($customer->getEntityId());
        $quote->setCurrency();
        $quote->assignCustomer($customer); // Assign quote to Customer

        //add items in quote
        foreach ($order['items'] as $item) {
            $product = $this->product->load($item['product_id']);
            $product->setPrice($item['price']);
            $quote->addProduct($product, intval($item['qty']));
        }

        $quote->getBillingAddress()->addData($order['shipping_address']);
        $quote->getShippingAddress()->addData($order['shipping_address']);

        // Collect Rates and Set Shipping & Payment Method

        $shippingAddress = $quote->getShippingAddress();
        $shippingAddress->setCollectShippingRates(true)->collectShippingRates()->setShippingMethod('freeshipping_freeshipping');
        $quote->setPaymentMethod('checkmo');
        $quote->setInventoryProcessed(false);
        $quote->save();

        // Set Sales Order Payment
        $quote->getPayment()->importData(['method' => 'checkmo']);

        // Collect Totals & Save Quote
        $quote->collectTotals()->save();

        // Create Order From Quote
        $orderdata = $this->quoteManagement->submit($quote);

        $orderdata->setEmailSent(0);
        $increment_id = $order->getRealOrderId();
        if ($orderdata->getEntityId()) {
            $result['order_id'] = $orderdata->getRealOrderId();
        } else {
            $result = ['error' => 1, 'msg' => 'Your custom message'];
        }
        return $result;
    }
}

?>

Reference https://meetanshi.com/blog/create-quote-order-programmatically-in-magento-2/

Hope it helps!

| improve this answer | |
  • HI Sumit, Create order for Simple and Configurable products works fine for me, but bundle products requires options to choose specifically, but i did not see anywhere you are selecting the option for the product. – user82154 Aug 30 '19 at 10:24
  • I've updated my answer, please check – Sumit Aug 30 '19 at 10:28
  • Hi Sumit, How do i add the Quantity of each option selection of bundle product. – user82154 Aug 31 '19 at 6:01
  • Pass quantity in the qty for the option you want to add in the first snippet I've shared above. – Sumit Aug 31 '19 at 6:12
  • I am Asking about Bundle Product Option Quantity, but you have mentioned the product Quantity, it not option quantity right? Also the same option parameter we are not setting in t he loop! – user82154 Aug 31 '19 at 6:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy