0

We have chunk of a code which helps to add Configurable product while placing order but the issue is only product shows inside order not options off the configurable product as displayed in following image.

Order Preview

Following code is used to placed the order please let me know if you found any bug inside the code.

require_once 'app/Mage.php';
umask(0);
Mage::app("default");

$recurringdata = array(
    "frequencytime" => "30",
    "payment" => array(
                    "cc_number" => "4111111111111111",
                    "cc_exp_month" => "10",
                    "cc_exp_year" => "2023",
                    "cc_cid" => "121",
                    "cc_type" => "VI"
                ),
    "billingadd" => "samebilling",
    "sku" => "TA",
    "first_name" => "banana",
    "last_name" => "banana",
    "email" => "banana.test@gmail.com",
    "phone" => "123456",
    "address" => "Test Address",
    "unit" => "202",
    "city" => "Arizona",
    "zip" => "86005",
    "country" => "US",
    "state" => "NY",
    "samplepro_name" => "",
    "samplepro_price" => "",
    "sampleprobuy" => "no",
    "samplepro_id" => "",
    "currentsku" => "TA",
    "shipping" => "$9.99",
    "tax_total" => "$4.05",
    "currentpro_name" => "Test Product",
    "currentpro_id" => "303",
    "currentpro_price" => "$60.00",
    "currentpro_single_price" => "$60.00",
    "currentpro_qty" => "1",
    "total" => "$74.04",
    "countryshippingadd" => "yes"
);
//print_r($recurringdata);exit;

$finalordertax = substr($recurringdata['tax_total'], 1);
$finalordershipping = substr($recurringdata['shipping'], 1);

$storeId = 1;

$transaction = Mage::getModel('core/resource_transaction');

$reservedOrderId = Mage::getSingleton('eav/config')->getEntityType('order')->fetchNewIncrementId($storeId);

$quoteObj = Mage::getModel('sales/quote')->setStoreId($storeId);
$quoteObj->setCustomerEmail($recurringdata['email']);

$Storecurrencycode = Mage::app()->getStore()->getCurrentCurrencyCode();
$Basecurrencycode = Mage::app()->getStore()->getBaseCurrencyCode();

$o_date = date('Y-m-d H:i:s');
$order = Mage::getModel('sales/order')
->setIncrementId($reservedOrderId)
->setStoreId($storeId)
->setQuoteId($quoteObj)
->setData('created_at',$o_date)
->setGlobal_currency_code($Storecurrencycode)
->setBase_currency_code($Basecurrencycode)
->setStore_currency_code($Storecurrencycode)
->setOrder_currency_code($Storecurrencycode);

// set Customer data
$order->setCustomer_email($recurringdata['email'])
    ->setCustomerFirstname($recurringdata['first_name'])
    ->setCustomerLastname($recurringdata['last_name'])
    ->setCustomer_is_guest('1');

// set Billing Address
if($recurringdata['billingadd'] == 'differentbelling'){
    $billingAddress = Mage::getModel('sales/order_address')
    ->setStoreId($storeId)
    ->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
    ->setFirstname($recurringdata['first_name'])
    ->setLastname($recurringdata['last_name'])
    ->setStreet($recurringdata['address'])
    ->setCity($recurringdata['city'])
    ->setCountry_id($recurringdata['country'])
    ->setRegion($recurringdata['state'])
    ->setPostcode($recurringdata['zip'])
    ->setTelephone($recurringdata['phone']);

    $billingstatelength = strlen($recurringdata['state']);
    if($billingstatelength == '2'){
        $regionmodel = Mage::getModel('directory/region')->loadByCode($recurringdata['state'], $recurringdata['country']);
        $billingstate_id = $regionmodel->getId();
        $billingAddress->setRegion_id($billingstate_id);
    }

    $order->setBillingAddress($billingAddress);
}else{
    $billingAddress = Mage::getModel('sales/order_address')
    ->setStoreId($storeId)
    ->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
    ->setFirstname($recurringdata['first_name'])
    ->setLastname($recurringdata['last_name'])
    ->setStreet($recurringdata['address'])
    ->setCity($recurringdata['city'])
    ->setCountry_id($recurringdata['country'])
    ->setRegion($recurringdata['state'])  
    ->setPostcode($recurringdata['zip'])
    ->setTelephone($recurringdata['phone']);

    $billingstatelength = strlen($recurringdata['state']);
    if($billingstatelength == '2'){
        $regionmodel = Mage::getModel('directory/region')->loadByCode($recurringdata['state'], $recurringdata['country']);
        $billingstate_id = $regionmodel->getId();
        $billingAddress->setRegion_id($billingstate_id);
    }

    $order->setBillingAddress($billingAddress);
}

//set Shipping Address
$shippingAddress = Mage::getModel('sales/order_address')
->setStoreId($setStoreId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
->setFirstname($recurringdata['first_name'])
->setLastname($recurringdata['last_name'])
->setStreet($recurringdata['address'])
->setCity($recurringdata['city'])
->setCountry_id($recurringdata['country'])
->setRegion($recurringdata['state'])  
->setPostcode($recurringdata['zip'])
->setTelephone($recurringdata['phone']);

$shippingstatelength = strlen($recurringdata['state']);
if($shippingstatelength == '2'){
    $regionmodel = Mage::getModel('directory/region')->loadByCode($recurringdata['state'], $recurringdata['country']);
    $shippingstate_id = $regionmodel->getId();
    $shippingAddress->setRegion_id($shippingstate_id);
}

$order->setShippingAddress($shippingAddress)
      ->setShipping_method('ups_03')
      ->setShippingDescription('UPS - UPS Ground')
      ->setShippingAmount($finalordershipping);

$cc_number = $recurringdata['payment']['cc_number'];
$orderPayment = Mage::getModel('sales/order_payment')
->setStoreId($storeId)
->setMethod('authnetcim')
->setCcNumber($cc_number)
->setCcType($recurringdata['payment']['cc_type'])
->setCcExpMonth($recurringdata['payment']['cc_exp_month'])
->setCcExpYear($recurringdata['payment']['cc_exp_year'])
->setCcLast4(substr($cc_number,-4))
->setCcCid($recurringdata['payment']['cc_cid']);
$order->setPayment($orderPayment);  

// add product
// 194 Is product id And 178 or 175 is my option id(super_attribute id)
$subTotal = 0;
$products = array(
    '194' => array(
        'qty' => '1',
        'price' => '$32.75',
        'super_attribute' => array(
            178 => 36,
            175 => 13
        )
    )
);

foreach ($products as $productId=>$product) {

    $finalorderpri = substr($product['price'], 1);
    $_product = Mage::getModel('catalog/product')->load($productId);
    $rowTotal = $finalorderpri * $product['qty'];
    $orderItem = Mage::getModel('sales/order_item')
    ->setStoreId($storeId)
    ->setQuoteItemId(0)
    ->setQuoteParentItemId(NULL)
    ->setProductId($productId)
    ->setProductType($_product->getTypeId())
    ->setQtyBackordered(NULL)
    ->setTotalQtyOrdered($product['qty'])
    ->setQtyOrdered($product['qty'])
    ->setName($_product->getName())
    ->setSku($_product->getSku())
    ->setPrice($finalorderpri)
    ->setBasePrice($_product->getPrice())
    ->setOriginalPrice($_product->getPrice())
    ->setRowTotal($rowTotal)
    ->setBaseRowTotal($rowTotal);

    $subTotal += $rowTotal;
    $order->addItem($orderItem);
}

$finalorderGrandTotal = ($subTotal + $finalordershipping + $finalordertax);

$order->setSubtotal($subTotal)
    ->setBaseSubtotal($subTotal)
    ->setGrandTotal($finalorderGrandTotal)
    ->setTaxAmount($finalordertax)
    ->setBaseGrandTotal($finalorderGrandTotal);

$transaction->addObject($order);
$transaction->addCommitCallback(array($order, 'place'));
$transaction->addCommitCallback(array($order, 'save'));     

try{
    $transaction->save();
    $order->save();
}catch(Exception $e){
    echo $e->getMessage();exit;
}

Please suggest me how super attribute set in configurable product when create order programatically.

2

Not sure what's wrong about your code, however here is one that works.

There is a class:

OrderGenerator.php

<?php

class OrderGenerator
{
    const CUSTOMER_RANDOM = null;

    protected $_shippingMethod = 'freeshipping_freeshipping';
    protected $_paymentMethod = 'cashondelivery';

    protected $_customer = self::CUSTOMER_RANDOM;

    protected $_subTotal = 0;
    protected $_order;
    protected $_storeId;

    public function setShippingMethod($methodName)
    {
        $this->_shippingMethod = $methodName;
    }

    public function setPaymentMethod($methodName)
    {
        $this->_paymentMethod = $methodName;
    }

    public function setCustomer($customer)
    {
        if ($customer instanceof Mage_Customer_Model_Customer){
            $this->_customer = $customer;
        }
        if (is_numeric($customer)){
            $this->_customer = Mage::getModel('customer/customer')->load($customer);
        }
        else if ($customer === self::CUSTOMER_RANDOM){
            $customers = Mage::getResourceModel('customer/customer_collection');

            $customers
                ->getSelect()
                ->limit(1)
                ->order('RAND()');

            $id = $customers->getFirstItem()->getId();

            $this->_customer = Mage::getModel('customer/customer')->load($id);
        }
    }

    public function createOrder($products)
    {
        if (!($this->_customer instanceof Mage_Customer_Model_Customer)){
            $this->setCustomer(self::CUSTOMER_RANDOM);
        }

        $transaction = Mage::getModel('core/resource_transaction');
        $this->_storeId = $this->_customer->getStoreId();
        $reservedOrderId = Mage::getSingleton('eav/config')
            ->getEntityType('order')
            ->fetchNewIncrementId($this->_storeId);

        $currencyCode  = Mage::app()->getBaseCurrencyCode();
        $this->_order = Mage::getModel('sales/order')
            ->setIncrementId($reservedOrderId)
            ->setStoreId($this->_storeId)
            ->setQuoteId(0)
            ->setGlobalCurrencyCode($currencyCode)
            ->setBaseCurrencyCode($currencyCode)
            ->setStoreCurrencyCode($currencyCode)
            ->setOrderCurrencyCode($currencyCode);


        $this->_order->setCustomerEmail($this->_customer->getEmail())
            ->setCustomerFirstname($this->_customer->getFirstname())
            ->setCustomerLastname($this->_customer->getLastname())
            ->setCustomerGroupId($this->_customer->getGroupId())
            ->setCustomerIsGuest(0)
            ->setCustomer($this->_customer);


        $billing = $this->_customer->getDefaultBillingAddress();
        $billingAddress = Mage::getModel('sales/order_address')
            ->setStoreId($this->_storeId)
            ->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
            ->setCustomerId($this->_customer->getId())
            ->setCustomerAddressId($this->_customer->getDefaultBilling())
            ->setCustomerAddress_id($billing->getEntityId())
            ->setPrefix($billing->getPrefix())
            ->setFirstname($billing->getFirstname())
            ->setMiddlename($billing->getMiddlename())
            ->setLastname($billing->getLastname())
            ->setSuffix($billing->getSuffix())
            ->setCompany($billing->getCompany())
            ->setStreet($billing->getStreet())
            ->setCity($billing->getCity())
            ->setCountry_id($billing->getCountryId())
            ->setRegion($billing->getRegion())
            ->setRegion_id($billing->getRegionId())
            ->setPostcode($billing->getPostcode())
            ->setTelephone($billing->getTelephone())
            ->setFax($billing->getFax())
            ->setVatId($billing->getVatId());
        $this->_order->setBillingAddress($billingAddress);

        $shipping = $this->_customer->getDefaultShippingAddress();
        $shippingAddress = Mage::getModel('sales/order_address')
            ->setStoreId($this->_storeId)
            ->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
            ->setCustomerId($this->_customer->getId())
            ->setCustomerAddressId($this->_customer->getDefaultShipping())
            ->setCustomer_address_id($shipping->getEntityId())
            ->setPrefix($shipping->getPrefix())
            ->setFirstname($shipping->getFirstname())
            ->setMiddlename($shipping->getMiddlename())
            ->setLastname($shipping->getLastname())
            ->setSuffix($shipping->getSuffix())
            ->setCompany($shipping->getCompany())
            ->setStreet($shipping->getStreet())
            ->setCity($shipping->getCity())
            ->setCountry_id($shipping->getCountryId())
            ->setRegion($shipping->getRegion())
            ->setRegion_id($shipping->getRegionId())
            ->setPostcode($shipping->getPostcode())
            ->setTelephone($shipping->getTelephone())
            ->setFax($shipping->getFax())
            ->setVatId($billing->getVatId());

        $this->_order->setShippingAddress($shippingAddress)
            ->setShippingMethod($this->_shippingMethod);

        $orderPayment = Mage::getModel('sales/order_payment')
            ->setStoreId($this->_storeId)
            ->setCustomerPaymentId(0)
            ->setMethod($this->_paymentMethod)
            ->setPoNumber(' – ');

        $this->_order->setPayment($orderPayment);

        $this->_addProducts($products);

        $this->_order->setSubtotal($this->_subTotal)
            ->setBaseSubtotal($this->_subTotal)
            ->setGrandTotal($this->_subTotal)
            ->setBaseGrandTotal($this->_subTotal);

        $transaction->addObject($this->_order);
        $transaction->addCommitCallback(array($this->_order, 'place'));
        $transaction->addCommitCallback(array($this->_order, 'save'));
        $transaction->save();        
    }

    protected function _addProducts($products)
    {
        $this->_subTotal = 0;

        foreach ($products as $productRequest) {
            if ($productRequest['product'] == 'rand') {

                $productsCollection = Mage::getResourceModel('catalog/product_collection');

                $productsCollection->addFieldToFilter('type_id', 'simple');
                Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($productsCollection);

                $productsCollection->getSelect()
                    ->order('RAND()')
                    ->limit(rand($productRequest['min'], $productRequest['max']));

                foreach ($productsCollection as $product){
                    $this->_addProduct(array(
                            'product' => $product->getId(),
                            'qty' => rand(1, 2)
                        ));
                }
            }
            else {
                $this->_addProduct($productRequest);
            }
        }
    }

    protected function _addProduct($requestData)
    {
        $request = new Varien_Object();
        $request->setData($requestData);

        $product = Mage::getModel('catalog/product')->load($request['product']);

        $cartCandidates = $product->getTypeInstance(true)
            ->prepareForCartAdvanced($request, $product);

        if (is_string($cartCandidates)) {
            throw new Exception($cartCandidates);
        }

        if (!is_array($cartCandidates)) {
            $cartCandidates = array($cartCandidates);
        }

        $parentItem = null;
        $errors = array();
        $items = array();
        foreach ($cartCandidates as $candidate) {
            $item = $this->_productToOrderItem($candidate, $candidate->getCartQty());

            $items[] = $item;

            /**
             * As parent item we should always use the item of first added product
             */
            if (!$parentItem) {
                $parentItem = $item;
            }
            if ($parentItem && $candidate->getParentProductId()) {
                $item->setParentItem($parentItem);
            }
            /**
             * We specify qty after we know about parent (for stock)
             */
            $item->setQty($item->getQty() + $candidate->getCartQty());

            // collect errors instead of throwing first one
            if ($item->getHasError()) {
                $message = $item->getMessage();
                if (!in_array($message, $errors)) { // filter duplicate messages
                    $errors[] = $message;
                }
            }
        }
        if (!empty($errors)) {
            Mage::throwException(implode("\n", $errors));
        }

        foreach ($items as $item){
            $this->_order->addItem($item);
        }

        return $items;
    }

    function _productToOrderItem(Mage_Catalog_Model_Product $product, $qty = 1)
    {
        $rowTotal = $product->getFinalPrice() * $qty;

        $options = $product->getCustomOptions();

        $optionsByCode = array();

        foreach ($options as $option)
        {
            $quoteOption = Mage::getModel('sales/quote_item_option')->setData($option->getData())
                ->setProduct($option->getProduct());

            $optionsByCode[$quoteOption->getCode()] = $quoteOption;
        }

        $product->setCustomOptions($optionsByCode);

        $options = $product->getTypeInstance(true)->getOrderOptions($product);

        $orderItem = Mage::getModel('sales/order_item')
            ->setStoreId($this->_storeId)
            ->setQuoteItemId(0)
            ->setQuoteParentItemId(NULL)
            ->setProductId($product->getId())
            ->setProductType($product->getTypeId())
            ->setQtyBackordered(NULL)
            ->setTotalQtyOrdered($product['rqty'])
            ->setQtyOrdered($product['qty'])
            ->setName($product->getName())
            ->setSku($product->getSku())
            ->setPrice($product->getFinalPrice())
            ->setBasePrice($product->getFinalPrice())
            ->setOriginalPrice($product->getFinalPrice())
            ->setRowTotal($rowTotal)
            ->setBaseRowTotal($rowTotal)

            ->setWeeeTaxApplied(serialize(array()))
            ->setBaseWeeeTaxDisposition(0)
            ->setWeeeTaxDisposition(0)
            ->setBaseWeeeTaxRowDisposition(0)
            ->setWeeeTaxRowDisposition(0)
            ->setBaseWeeeTaxAppliedAmount(0)
            ->setBaseWeeeTaxAppliedRowAmount(0)
            ->setWeeeTaxAppliedAmount(0)
            ->setWeeeTaxAppliedRowAmount(0)

            ->setProductOptions($options);

        $this->_subTotal += $rowTotal;

        return $orderItem;
    }
}

And you use it like in the following example:

<?php

require_once 'app/Mage.php';
umask(0);
Mage::app('default');

require_once 'OrderGenerator.php';

function create_order_with_custom_products()
{
    $orderGenerator = new OrderGenerator();

    $orderGenerator->createOrder(array(
        // Add configurable product
        array(
            'product' => 418,
            'super_attribute' => array(
                92 => 26,
                180 => 79
            ),
            'qty' => 1
        ),
        // Add products with custom options
        array(
            'product' => 553,
            'options' => array(
                11 => 8
            ),
            'qty' => 2
        ),
        array(
            'product' => 553,
            'options' => array(
                11 => 9
            ),
            'qty' => 1
        ),
        // Add 1-3 random simple products
        array(
               'product' => 'rand',
               'min' => 1,
               'max' => 3
        ),
    ));
}

Where child products are set for configurable item with the following construction:

'super_attribute' => array(
    92 => 26,
    180 => 79
),
  • Hi @Amasty Thanks for your help, I check your code and it's works perfectly. – Vithal Bariya Jun 17 '16 at 11:16

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.