Reading list Switch to dark mode

    Programmatically Create Order In Magento

    Updated 23 February 2024

    Here we learn how to create order programmatically in Magento2

    First we will create a Controller name Index.php in  app/code/Namespace/Modulename/Controller/adminhtml/Order

    <?php
    namespace NameSpace\ModuleName\Controller\Adminhtml\Order;
    
    class Index extends \Magento\Backend\App\Action
    {
        /**
         * @var Magento\Framework\App\Action\Context
         */
        protected $context;
        /**
         * @var Magento\Store\Model\StoreManagerInterface
         */
        protected $_storeManager;
        /**
         * @var \Magento\Catalog\Model\Product
         */
        protected $_product;
        /**
         * @var \Magento\Framework\Data\Form\FormKey
         */
        protected $_formkey;
        /**
         * @var \Magento\Quote\Model\QuoteFactory
         */
        protected $quote;
        /**
         * @var \Magento\Quote\Model\QuoteManagement
         */
        protected $quoteManagement;
        /**
         * @var \Magento\Customer\Model\CustomerFactory
         */
        protected $customerFactory;
        /**
         * @var $product
         */
        protected $customerRepository;
        /**
         * @var $product
         */
        protected $orderService;
    
        /**
        * @param Magento\Framework\App\Action\Context $context
        * @param Magento\Store\Model\StoreManagerInterface $storeManager
        * @param Magento\Catalog\Model\Product $product
        * @param Magento\Framework\Data\Form\FormKey $formKey $formkey,
        * @param Magento\Quote\Model\Quote $quote,
        * @param Magento\Quote\Model\QuoteManagement $quoteManagement,
        * @param Magento\Customer\Model\CustomerFactory $customerFactory,
        * @param Magento\Customer\Api\CustomerRepositoryInterface $customerRepository
        */
        public function __construct(
            \Magento\Backend\App\Action\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
        ) {
            $this->_storeManager = $storeManager;
            $this->_product = $product;
            $this->_formkey = $formkey;
            $this->quote = $quote;
            $this->quoteManagement = $quoteManagement;
            $this->customerFactory = $customerFactory;
            $this->customerRepository = $customerRepository;
            parent::__construct($context);
        }
    
        /**
         * Create order controller page.
         *
         * @return \Magento\Backend\Model\View\Result\Page
         */
        public function execute()
        {
            $productids=array(1);
            $store = $this->_storeManager->getStore();
            $websiteId = $this->_storeManager->getStore()->getWebsiteId();
            // Start New Sales Order Quote
            $quote=$this->quote->create(); //Create object of quote
            $quote->setStore($store); //set store for which you create quote
            // Set Sales Order Quote Currency
            $email = '[email protected]'; // set your custom mail
            $customer = $this->customerFactory->create()
                        ->setWebsiteId($websiteId)
                        ->loadByEmail($email);
            if($customer->getId()==""){
                $customer = $this->customerFactory->create();
                $customer->setWebsiteId($websiteId)
                        ->setStore($store)
                        ->setFirstname('Jhon')
                        ->setLastname('Deo')
                        ->setEmail($email)
                        ->setPassword("password");
                $customer->save();
            }
            $customer= $this->customerRepository->getById($customer->getEntityId());
            $quote->setCurrency();
    
            // Assign Customer To Sales Order Quote
            $quote->assignCustomer($customer);
        
                // Configure Notification
            $quote->setSendConfirmation(1);
            foreach($productids as $id){
                $product = $this->_product->load($id);
                $quote->addProduct($product, intval(array('qty'   => 1)));
            }
        
            // Set Sales Order Billing Address
            $billingAddress = $quote->getBillingAddress()->addData(array(
                'customer_address_id' => '',
                'prefix' => '',
                'firstname' => 'john',
                'middlename' => '',
                'lastname' =>'Deo',
                'suffix' => '',
                'company' =>'', 
                'street' => array(
                        '0' => 'Noida',
                        '1' => 'Sector 64'
                    ),
                'city' => 'Noida',
                'country_id' => 'IN',
                'region' => 'UP',
                'postcode' => '201301',
                'telephone' => '78676789',
                'fax' => 'gghlhu',
                'vat_id' => '',
                'save_in_address_book' => 1
            ));
        
            // Set Sales Order Shipping Address
           $shippingAddress = $quote->getShippingAddress()->addData(array(
                'customer_address_id' => '',
                'prefix' => '',
                'firstname' => 'john',
                'middlename' => '',
                'lastname' =>'Deo',
                'suffix' => '',
                'company' =>'', 
                'street' => array(
                        '0' => 'Noida',
                        '1' => 'Sector 64'
                    ),
                'city' => 'Noida',
                'country_id' => 'IN',
                'region' => 'UP',
                'postcode' => '201301',
                'telephone' => '78676789',
                'fax' => 'gghlhu',
                'vat_id' => '',
                'save_in_address_book' => 1
            ));
    
            // Collect Rates and Set Shipping & Payment Method
            $shippingAddress->setCollectShippingRates(true)
                            ->collectShippingRates()
                            ->setShippingMethod('flatrate_flatrate')
                            ->setPaymentMethod('checkmo');
    
            $quote->setPaymentMethod('checkmo'); //payment method
            $quote->setInventoryProcessed(false); //not effetc inventory
            $quote->save(); //Now Save quote and your quote is ready
    
            // Set Sales Order Payment
            $quote->getPayment()->importData(array('method' => 'checkmo'));
        
            // Collect Totals & Save Quote
            $quote->collectTotals()->save();
        
            // Create Order From Quote
            $service = $this->quoteManagement->submit($quote);
            $increment_id = $service->getRealOrderId();
        
            // Resource Clean-Up
            $quote = $customer = $service = null;
        
            // Finished
            echo __('Order created successfully with order id '.$increment_id);
        }
    }

    Now Your order created successfully.

    thanks 🙂

    Searching for an experienced
    Magento Company ?
    Find out More
    . . .

    Leave a Comment

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


    19 comments

  • kalpesh patel
    • Jaydip Kansagra
  • kalpesh patel
  • MagentoUser
  • Pranav
  • Jenish Khunt
  • TAhmed
    • webkul
      • TAhmed
        • Jaydip Kansagra
  • Sampathi Ramakrishna
    • webkul
  • udit gupta
  • theunknown
  • chaosratt
    • webkul
      • Mitesh Patel
        • webkul
      • chaosratt
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home