1

I just added the custom order form on my products page(form.phtml) as below image to create order. Based on this input values orders should created and also custom email need to send with the form details. After submitting, custom email is sending but the order is not creating.

enter image description here

my custom module's Data.php

<?php
namespace Company\Module\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
     /**
    * @param Magento\Framework\App\Helper\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\Customer\Model\CustomerFactory $customerFactory,
    * @param Magento\Sales\Model\Service\OrderService $orderService,
    */
    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,
        \Magento\Quote\Api\CartRepositoryInterface $cartRepositoryInterface, 
        \Magento\Quote\Api\CartManagementInterface $cartManagementInterface,
        \Magento\Quote\Model\Quote\Address\Rate $shippingRate 
    ) {
        $this->_storeManager = $storeManager;
        $this->_product = $product;
        $this->_formkey = $formkey;
        $this->quote = $quote;
        $this->quoteManagement = $quoteManagement;
        $this->customerFactory = $customerFactory;
        $this->customerRepository = $customerRepository;
        $this->orderService = $orderService;
        $this->cartRepositoryInterface = $cartRepositoryInterface;
        $this->cartManagementInterface = $cartManagementInterface;
        $this->shippingRate = $shippingRate;
        parent::__construct($context);
    }

    /**
     * Create Order On my Store
     * 
     * @param array $orderData
     * @return array
     * 
    */


  public function CreateOrder($productData, $userData) {

        $store = $this->_storeManager->getStore();
        $storeid = $this->_storeManager->getStore()->getId();
        $websiteId = $this->_storeManager->getStore()->getWebsiteId();

        $productId = $this->_product->getIdBySku($productData['sku']); // Bundle Product SKU

        $params = array(
            'product' =>  $productId
        );

        $request = new \Magento\Framework\DataObject();
        $request->setData($params);

        $_value['Email'] = $userData['email'];
        $_value['First Name'] = $userData['firstname'];
        $_value['Last Name'] = $userData['lastname'];
        $_value['Address'] = $userData['address'];
        $_value['City'] = $userData['city'];
        $_value['Telephone'] = $userData['telephone'];

        // create customer
        $customer = $this->customerFactory->create();
        $password = 'xxxxxxx';

        $customer->setWebsiteId($websiteId); // Set Website ID
        $customer->loadByEmail($_value['Email']);
     //   $customer->setWebsiteId(1); // Set Website ID AGAIN!

        if(!$customer->getEntityId()){
            //If not avilable then create this customer
            $customer->setWebsiteId($websiteId)
                ->setStore($store)
                ->setFirstname($_value['First Name'])
                ->setLastname($_value['Last Name'])
                ->setEmail($_value['Email'])
                ->setPassword($password);
            $customer->save();
        }

        $quote=$this->quote->create(); //Create object of quote
        $quote->setStore($store); //set store for which you create quote

        $customer= $this->customerRepository->getById($customer->getEntityId());
        $quote->setCurrency();
        $quote->assignCustomer($customer); //Assign quote to customer

        $dataShipping = array(
            'firstname'  => $_value['First Name'],
            'lastname'   => $_value['Last Name'],
            'street'     => $_value['Address'],
            'city'       => $_value['City'],
            'region'     => '',
            'region_id'  => '',
            'country_id' => 'INR', //todo: un-hardcode this.
            'postcode' => '12345',
            'telephone'  => $_value['Telephone'],
        );


        $product = $this->_product->load($productId);
        $product->setPrice($productData['price']);

        $quote->addProduct($product, $request);
        $quote->setCustomer($customer);
        $quote->assignCustomer($customer);


        $quote->getShippingAddress()->addData($dataShipping)->setShippingMethod('freeshipping_freeshipping');
        $quote->getShippingAddress()->setShippingMethod('freeshipping_freeshipping');
        $quote->getShippingAddress()->setCollectShippingRates(true);
        $quote->getShippingAddress()->collectShippingRates(); 
        $quote->setPayment($quote->getPayment()->setMethod('free'));


        $quote->collectTotals();


        $quote->save();

        $convertQuoteObj = $this->quoteManagement;
        $orderObj = $convertQuoteObj->submit($quote);

        $orderPaymentObj=$convertQuoteObj->paymentToOrderPayment($quote->getPayment());

        $orderObj->setBillingAddress($convertQuoteObj->addressToOrderAddress($quote->getBillingAddress()));
        $orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quote->getPayment()));
        $orderObj->setShippingAddress($convertQuoteObj->addressToOrderAddress($quote->getShippingAddress()));


        $qty = $productData['quantity'];

        foreach ($quote->getShippingAddress()->getAllItems() as $item) {
            //@var $item Mage_Sales_Model_Quote_Item
            $item->setQty($qty);
            $orderItem = $convertQuoteObj->itemToOrderItem($item);
            if ($item->getParentItem()) {
                $orderItem->setParentItem($orderObj->getItemByQuoteItemId($item->getParentItem()->getId()));
            }
            $orderObj->addItem($orderItem);
        }

          $orderObj->setCustomerNote($productData['customernote']);

          $orderObj->setSubtotal($productData['price']);
          $orderObj->setBaseSubtotal($productData['price']);

          $orderObj->setGrandTotal($productData['price']);
          $orderObj->setBaseGrandTotal($productData['price']);

        $orderObj->setStoreId($storeid);

        $orderObj->setCanShipPartiallyItem(false);

        $totalDue=$orderObj->getTotalDue();

        $orderObj->place(); //calls _placePayment
        $orderObj->save();
        return $orderId=$orderObj->getId();

    }

}

my custom module's Index.php

<?php
namespace Company\Module\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;
use Magento\Framework\App\Request\DataPersistorInterface;


class Index extends \Magento\Framework\App\Action\Action
{
    private $dataPersistor;
    /**
     * @return \Magento\Framework\Controller\Result\Redirect|\Magento\Framework\View\Result\Page
     */

    protected $context;
    private $fileUploaderFactory;
    private $fileSystem;


    /**
     * @var \Magento\Framework\Mail\Template\TransportBuilder
     */
    protected $_transportBuilder;

    /**
     * @var \Magento\Framework\Translate\Inline\StateInterface
     */
    protected $inlineTranslation;

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */


    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder
     * @param \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     */

     public function __construct(
        \Magento\Framework\App\Action\Context $context,
        Filesystem $fileSystem,
        \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory,
        \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
        \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    ) {
        parent::__construct($context,$transportBuilder,$inlineTranslation, $scopeConfig );
        $this->fileUploaderFactory = $fileUploaderFactory;
        $this->fileSystem          = $fileSystem;
        $this->_transportBuilder = $transportBuilder;
        $this->inlineTranslation = $inlineTranslation;
        $this->scopeConfig = $scopeConfig;
    }

    public function execute()
    {


        $quantity = $this->getRequest()->getParam('quantity');
        $productname = $this->getRequest()->getParam('productname');
        $name = $this->getRequest()->getParam('name'); 
        $lname = $this->getRequest()->getParam('lname');
        $email = $this->getRequest()->getParam('email'); 
        $mobile= $this->getRequest()->getParam('mobile'); 
        $address= $this->getRequest()->getParam('address'); 
        $city = $this->getRequest()->getParam('city'); 
        $country= $this->getRequest()->getParam('country'); 
        $comments= $this->getRequest()->getParam('comments'); 
        $price = $this->getRequest()->getParam('totalprice'); 


          $productData = 
          array('sku' => $model, 'quantity'=> $quantity,
          'price'=>str_replace(",","", $price),
          'customernote'=>$comments."<br/>".$extrainfo
          );

          $concat_address= $address;

          $userData = array('email'=>$email,
            'firstname'=>$name,'lastname'=>$lname,'address'=>$concat_address,
            'city'=>$city,'telephone'=>$mobile);

          $orderid = $this->_objectManager->create('Company\Module\Helper\Data')->CreateOrder($productData, $userData); (I know its not good approach but for testing I tried)



        $sent_output = "";

        $sent_output .= "<body>";

        $sent_output .= "<div style=\"margin:5px; padding:10px; border-bottom:1px solid #CCCCCC; \">";

        $sent_output .= "<p style=\"font-size:14px; font-weight:bold; margin:5px 0px 0px 0px; font-family:Arial, Helvetica, sans-serif; padding:0px;\">ORDER SUMMARY</p>";

        $sent_output .= "<p style=\"font-family:Arial, Helvetica, sans-serif; font-size:12px; margin:0px; padding:0px;\"><span style=\"width:120px; float:left;\">PRODUCT</span>: " . $productname . "</p>";


        $sent_output .= "<p style=\"font-family:Arial, Helvetica, sans-serif; font-size:12px; margin:0px; padding:0px;\"><span style=\"width:120px; float:left;\">NAME</span>: " . $name . "</p>";

        $sent_output .= "<p style=\"font-family:Arial, Helvetica, sans-serif; font-size:12px; margin:0px; padding:0px;\"><span style=\"width:120px; float:left;\">EMAIL</span>: " . $email . "</p>";

        $sent_output .= "<p style=\"font-family:Arial, Helvetica, sans-serif; font-size:12px; margin:0px; padding:0px;\"><span style=\"width:120px; float:left;\">MOBILE</span>: " . $mobile . "</p>";

        $sent_output .= "<p style=\"font-family:Arial, Helvetica, sans-serif; font-size:12px; margin:0px; padding:0px;\"><span style=\"width:120px; float:left;\">ADDRESS</span>: " . $address . "</p>";

        $sent_output .= "<p style=\"font-family:Arial, Helvetica, sans-serif; font-size:12px; margin:0px; padding:0px;\"><span style=\"width:120px; float:left;\">REMARKS</span>: " . $comments . "</p>";

        $sent_output .= "<p style=\"font-family:Arial, Helvetica, sans-serif; font-size:12px; margin:0px; padding:0px;\"><span style=\"width:120px; float:left;\">CITY</span>: " . $city . "</p>";

        $sent_output .= "<p style=\"font-family:Arial, Helvetica, sans-serif; font-size:12px; margin:0px; padding:0px;\"><span style=\"width:120px; float:left;\">COUNTRY</span>: " . $country . "</p>";


        $sent_output .= "</div>";

        $sent_output .= "<p style=\"font-family:Arial, Helvetica, sans-serif; font-size:12px; margin:0px; padding:0px;\"><span style=\"width:120px; float:left;\">QUANTITY</span>: " . $quantity . "</p>";
        $sent_output .= "<p style=\"font-family:Arial, Helvetica, sans-serif; font-size:12px; margin:0px; padding:0px;\"><span style=\"width:120px; float:left;\">TOTAL</span>: Rs." . $price . "</p>";

        $sent_output .= "</div>";

        $sent_output .= "<div style='margin-left:18px;'>";
        $sent_output .= "<p style=\"font-family:Arial, Helvetica, sans-serif;  font-size:12px; margin:0px; padding:0px;font-weight:bold\"> " . $extrainfo . "</p>";
        $sent_output .= "</div>";

        $sent_output .= "</body>";



        $customerName='Demo Form';
        $message=$sent_output;

        $userSubject= 'Demo From ';     
        $fromEmail= 'test123@gmail.com';
        $fromName = 'Test Demo Form';

         $templateVars = [
                    'store' => 1,
                    'customer_name' => $name,
                    'customer_email' => $email,
                    'subject' => $userSubject,
                    'message'   => $message
                ];
        $from = ['email' => $fromEmail, 'name' => $fromName];
        $this->inlineTranslation->suspend();


        $to = $email;     

        $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;

         $templateOptions = [
          'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
          'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID
        ];

        $transport = $this->_transportBuilder->setTemplateIdentifier('extra_email_template')
                ->setTemplateOptions($templateOptions)
                ->setTemplateVars($templateVars)
                ->setFrom($from)
                ->addTo($to)            
                ->getTransport();
        $transport->sendMessage();
        $this->inlineTranslation->resume();

        $this->messageManager->addSuccess(__('Form successfully submitted'));

        $this->_redirect('form');
    }

}

Can anyone correct this and Why order is not creating?

Thanks.

  • Hi Selva, this is quite a lot of code and very little debug information. What have you tried to find a solution, did you pinpoint it to a specific part of the code like for example creating the address? Being more specific will give you better answers – Sander Mangel Aug 7 '18 at 5:17
  • @SanderMangel its very simple, orders should be created based on input values on my custom form on product page. Can you please let me know how to achieve this? – Mesk Aug 7 '18 at 5:25
  • @SanderMangel, yes you are right. I am struggle with creating the address. Please check the code – Mesk Aug 7 '18 at 5:28
  • If it were simple you wouldn't be posting here ;) what did you try so far? – Sander Mangel Aug 7 '18 at 5:34
  • I just said it to understand my question Sander, please don't mistake. As you said its quite complicated I know – Mesk Aug 7 '18 at 5:37

Your Answer

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

Browse other questions tagged or ask your own question.