Created a custom form where customer and product details filled with status of Active/Not active So for now I want to create an event and observer to place order programmatically when status is Active from admin panel, place order on the bases of customer, product

  • What about shipping and payment?
    – Ankit
    Mar 30, 2021 at 5:14
  • Shipping should be flat rate and payment should be cash on delivery Mar 30, 2021 at 6:36

3 Answers 3


1)Create event.xml file:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="sales_order_place_after">
        <observer name="neo_ordercomment_observer_orderneo" instance="vendor\module\Observer\Orderneo" />

2)Create PlaceOrder.php file in Observer directory:


namespace Vendor\Module\Observer;

class PlaceOrder implements \Magento\Framework\Event\ObserverInterface
    public function execute(\Magento\Framework\Event\Observer $observer)
        $order= $observer->getData('order');
        $comment = $this->getRequest()->getParams('comment');
        print_r("Catched event succssfully !"); exit;
  • This is after event, I want to create order programmatically when custom table (row) status is active Mar 30, 2021 at 6:33

May be these articles can help you, as I think you have built a custom module already to fill the customer and product details, I know you asked for event, but if its custom module, you will have to create your own event using dispatch event:



  • They don't use event observer Mar 30, 2021 at 6:45
  • @ArunKumar If you do have custom form why you want to use event observer, please describe in detail.
    – Ankit
    Mar 30, 2021 at 6:54
  • @Ankit I have a custom form where I am getting details from user, it getting save in a table and visible in admin grid, there is a toggle for Active/Disable, So if admin change toggle to Active and Save the product, order place automatically for the particular product which is Active. This is the description. Can you please suggest how this can be done Mar 30, 2021 at 7:02
  • join here pls chat.stackexchange.com/rooms/122439/…
    – Ankit
    Mar 30, 2021 at 7:13
  • Sure I just join Mar 30, 2021 at 7:36

Created custom event for this


<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="trigger_order_place">
        <observer name="vtn_order_success" instance="Vtn\Investment\Observer\Orderplace" />

Here I am getting data dynamically for place order programatically, you can use static values or get your data as per your collection observer -> Orderplace.php

namespace Vtn\Investment\Observer;

use \Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class Orderplace implements ObserverInterface
    * @param Magento\Store\Model\StoreManagerInterface $storeManager,
    * @param Magento\Customer\Model\CustomerFactory $customerFactory,
    * @param Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
    * @param Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
    * @param Magento\Quote\Model\QuoteFactory $quote,
    * @param Magento\Quote\Model\QuoteManagement $quoteManagement,
    * @param Magento\Sales\Model\Order\Email\Sender\OrderSender $orderSender,
    * @param Magento\Sales\Model\Order $orderCollectionFactory,
    * @param Vtn\Investment\Model\InvestmentFactory $investmentFactory

    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
        \Magento\Quote\Model\QuoteFactory $quote,
        \Magento\Quote\Model\QuoteManagement $quoteManagement,
        \Magento\Sales\Model\Order\Email\Sender\OrderSender $orderSender,
        \Magento\Sales\Model\Order $orderCollectionFactory,
        \Vtn\Investment\Model\InvestmentFactory $investmentFactory
        $this->storeManager = $storeManager;
        $this->customerFactory = $customerFactory;
        $this->productRepository = $productRepository;
        $this->customerRepository = $customerRepository;
        $this->quote = $quote;
        $this->quoteManagement = $quoteManagement;
        $this->orderSender = $orderSender;
        $this->orderCollectionFactory = $orderCollectionFactory;
        $this->investmentFactory = $investmentFactory;

    public function execute(Observer $observer)
        $collection = $observer->getEvent()->getCollection();
        $collectionData = $collection->getData();
        $Approve = $collection->getActive();
        $investmentId = $collection->getId();
        $customerId = $collection->getCustomerId();
        $vtnOrderId = $collection->getOrderId();
        $customerModel = $this->customerRepository->getById($customerId);
        $currency = $this->storeManager->getStore()->getCurrentCurrency();

        // cencel order if investment discard
        if($Approve == '0' && $vtnOrderId != ''){
            $order = $this->orderCollectionFactory->load($vtnOrderId);

            $productInvest = $this->investmentFactory->create()->getCollection()->addFieldToFilter('id', $investmentId);
            foreach($productInvest as $data){
                $models = $this->investmentFactory->create()->load($data->getId());

        // create order when user approve investment request
        if($Approve == '1' && $vtnOrderId == ''){            
            foreach ($customerModel->getAddresses() as $address) {
                $orderInfo =[
                    'currency_id'  => $currency,
                    'email'        => $collection->getCustomerEmail(),
                    'address' =>[
                        'firstname' => $address->getFirstname(),
                        'lastname' => $address->getLastname(),
                        'prefix' => $address->getPrefix(),
                        'suffix' => $address->getSuffix(),
                        'street' => $address->getStreet(),
                        'city' => $address->getCity(),
                        'country_id' => $address->getCountryId(),
                        'region' => $address->getRegion(),
                        'region_id' => $address->getRegionId(),
                        'postcode' => $address->getPostcode(),
                        'telephone' => $address->getTelephone(),
                        'fax' => $address->getFax(),
                        'save_in_address_book' => 1
                            ['product_id'=> $collection->getProductId(),'qty'=>1],
            $store = $this->storeManager->getStore();
            $storeId = $store->getStoreId();
            $websiteId = $this->storeManager->getStore()->getWebsiteId();
            $customer = $this->customerFactory->create();
            $customer->loadByEmail($orderInfo['email']);// load customet by email address
            $quote=$this->quote->create(); //Create object of quote
            $quote->setStore($store); //set store for our quote
            $customer= $this->customerRepository->getById($customer->getId());
            $quote->assignCustomer($customer); //Assign quote to customer
            //add items in quote
            foreach($orderInfo['items'] as $item){
                if(!empty($item['super_attribute']) ) {
                    /* for configurable product */
                    $buyRequest = new \Magento\Framework\DataObject($item);
                } else {
                    /* for simple product */
            //Set Billing and shipping Address to quote
            // set shipping method
                            //shipping method, please verify free shipping must be enable
            //payment method, please verify checkmo must be enable from admin
            //decrease item stock equal to qty
            $quote->save();  //quote save 
            // Set Sales Order Payment, We have taken check/money order
            $quote->getPayment()->importData(['method' => 'checkmo']);
            // Collect Quote Totals & Save
            // Create Order From Quote Object
            $order = $this->quoteManagement->submit($quote);
            /* for send order email to customer email id */
            /* get order real id from order */
            $orderId = $order->getIncrementId();

            // Investment order column to yes 
            $order = $this->orderCollectionFactory->load($orderId);

            // save order id in vtn_investment_req table
            $productInvest = $this->investmentFactory->create()->getCollection()->addFieldToFilter('id', $investmentId);
            foreach($productInvest as $data){
                $models = $this->investmentFactory->create()->load($data->getId());

                $result['success']= $orderId;
                $result=['error'=>true,'msg'=>'Something Went Wrong During Order Placement'];
            return $result;
        return $this;

Controller where event is dispatch Save.php

public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \Vtn\Investment\Model\InvestmentFactory $investmentFactory,
        EventManager $eventManager
        $this->resultPageFactory = $resultPageFactory;
        $this->investmentFactory = $investmentFactory;
        $this->eventManager = $eventManager;

    public function execute()
        $resultRedirect = $this->resultRedirectFactory->create();
        $data = $this->getRequest()->getPostValue();
        $id = $data['id'];
                $id = $data['id'];
                $investment = $this->investmentFactory->create()->load($id);
                $data = array_filter($data, function($value) {return $value !== ''; });
                $collection = $investment->setData($data);

                // dispatch custom event for order place
                $this->eventManager->dispatch('trigger_order_place',['collection' => $collection]);

                $this->messageManager->addSuccess(__('Successfully saved the item.'));
                return $resultRedirect->setPath('*/*/');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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