Magento 1.8 Orders – Programmatically Create an Order of Grouped and Bundle Product in Magento

bundled-productce-1.8.1.0grouped-productsmagento-1.8orders

I need a code to create order in Magento programmatically.

I used this script for simple product order and it works good.

require_once 'app/Mage.php'; 
Mage::app(); 
$quote = Mage::getModel('sales/quote')
        ->setStoreId(Mage::app()->getStore('default')->getId());
        $customer = Mage::getModel('customer/customer')
                ->setWebsiteId(1)
                ->loadByEmail('test@example.com');
        $quote->assignCustomer($customer); 
$product = Mage::getModel('catalog/product')->load(2770);
$buyInfo = array(
        'qty' => 1, 
);
$quote->addProduct($product, new Varien_Object($buyInfo)); 
$addressData = array(
        'firstname' => 'Test',
        'lastname' => 'Test',
        'street' => 'Sample Street 10',
        'city' => 'Somewhere',
        'postcode' => '123456',
        'telephone' => '123456',
        'country_id' => 'US',
        'region_id' => 12, // id from directory_country_region table
); 
$billingAddress = $quote->getBillingAddress()->addData($addressData);
$shippingAddress = $quote->getShippingAddress()->addData($addressData);

$shippingAddress->setCollectShippingRates(true)->collectShippingRates()
                ->setShippingMethod('freeshipping_freeshipping')
                ->setPaymentMethod('checkmo');
$quote->getPayment()->importData(array('method' => 'checkmo'));
$quote->collectTotals()->save();
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();
$order = $service->getOrder();
printf("Created order %s\n", $order->getIncrementId());

But i also want to create order of grouped product as well as bundle product,
I try with using grouped and bundle product id but it does not work

Best Answer

Don't use Mage_Sales_Model_Quote::addProduct(), especially for complex products. Use Mage_Checkout_Model_Cart::addProduct() which is also used by the add to cart controller action and takes care for configuring the product and quote item. It takes a product id and the "request info" as parameters, where the request info can be simply the qty to buy (for simple products) or data for a buyRequest object. This is basically the $_POST data from an add to cart action.

So have a look at what form data is sent to Magento when adding a grouped or bundled product to the cart, then you can simulate this request with:

Mage::getSingleton('checkout/cart')->addProduct($productId, $request);

You can read more about the buyRequest in this reference.

Related Topic