0

I am creating order at controller action, just to test if its working or not as:

class Save extends \Magento\Framework\App\Action\Action
{
 /**
    * @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  
    ) {
        $this->_storeManager = $storeManager;
        $this->_product = $product;
        $this->_formkey = $formkey;
        $this->quote = $quote;
        $this->quoteManagement = $quoteManagement;
        $this->customerFactory = $customerFactory;
        $this->customerRepository = $customerRepository;
        $this->orderService = $orderService;
        parent::__construct($context);
    }

    /**
     * Create Order On Your Store
     * 
     * @param array $orderData
     * @return array
     * 
    */
    public function createMageOrder($orderData) {
        $store=$this->_storeManager->getStore();
        $websiteId = $this->_storeManager->getStore()->getWebsiteId();
        $customer=$this->customerFactory->create();
        $customer->setWebsiteId($websiteId);
        $customer->loadByEmail($orderData['email']);// load customet by email address
        263135
        if(!$customer->getEntityId()){
            //If not avilable then create this customer 
            $customer->setWebsiteId($websiteId)
                    ->setStore($store)
                    ->setFirstname($orderData['shipping_address']['firstname'])
                    ->setLastname($orderData['shipping_address']['lastname'])
                    ->setEmail($orderData['email']) 
                    ->setPassword($orderData['email']);
            $customer->save();
        }
        $quote=$this->quote->create(); //Create object of quote
        $quote->setStore($store); //set store for which you create quote
        // if you have allready buyer id then you can load customer directly 
        $customer= $this->customerRepository->getById($customer->getEntityId());
        $quote->setCurrency();
        $quote->assignCustomer($customer); //Assign quote to customer

        //add items in quote
        foreach($orderData['items'] as $item){
            $product=$this->_product->load($item['product_id']);
            $product->setPrice($item['price']);
            $quote->addProduct(
                $product,
                intval($item['qty'])
            );
        }

        //Set Address to quote
        $quote->getBillingAddress()->addData($orderData['shipping_address']);
        $quote->getShippingAddress()->addData($orderData['shipping_address']);

        // Collect Rates and Set Shipping & Payment Method

        $shippingAddress=$quote->getShippingAddress();
        $shippingAddress->setCollectShippingRates(true)
                        ->collectShippingRates()
                        ->setShippingMethod('freeshipping_freeshipping'); //shipping method
        $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(['method' => 'checkmo']);

        // Collect Totals & Save Quote
        $quote->collectTotals()->save();

        // Create Order From Quote
        $order = $this->quoteManagement->submit($quote);

        $order->setEmailSent(0);
        $increment_id = $order->getRealOrderId();
        if($order->getEntityId()){
            $result['order_id']= $order->getRealOrderId();
        }else{
            $result=['error'=>1,'msg'=>'Your custom message'];
        }
        return $result;
    }
    public function execute()
    {
        $orderData=[
                    'currency_id' => 'USD',
                    'email' => 'user@w3classes.info', //customer email id
                    'shipping_address' =>[
                    'firstname' => 'Test', //address Details
                    'lastname' => 'User',
                    'street' => '123 main street',
                    'city' => 'Demo',
                    'country_id' => 'US',
                    'region' => 'xxx', // replace with region
                    'postcode' => 'XXXXX', // replace with real zip code
                    'telephone' => '9999999999',
                    'save_in_address_book' => 1 // If you want to save in address book
                    ],
                    'items'=> [ //array of products for which you want to create order.
                    ['product_id'=>'5','qty'=>2]
                    ]
                    ];

       $orderID = $this->createOrder($orderData);
       echo $orderID;
    $resultRedirect = $this->resultRedirectFactory->create();
    $resultRedirect->setPath('frontname/index/index');
    return $resultRedirect;
}

Almost all links available are explaining same:

https://www.w3classes.info/create-order-programatically-in-magento-2/ https://www.mageplaza.com/devdocs/magento-2-create-order-programmatically.html

but when I do this I am having error:

Fatal error: Uncaught TypeError: Argument 2 passed to Magento\Eav\Model\Attribute\Data\Text::validateLength() must be of the type string, null given, called in /var/www/html/vendor/magento/module-eav/Model/Attribute/Data/Text.php on line 80 and defined in /var/www/html/vendor/magento/module-eav/Model/Attribute/Data/Text.php:141 Stack trace: #0 /var/www/html/vendor/magento/module-eav/Model/Attribute/Data/Text.php(80): Magento\Eav\Model\Attribute\Data\Text->validateLength(Object(Magento\Customer\Model\Attribute), NULL) #1 /var/www/html/vendor/magento/module-eav/Model/Validator/Attribute/Data.php(131): Magento\Eav\Model\Attribute\Data\Text->validateValue(NULL) #2 /var/www/html/vendor/magento/framework/Validator/Constraint.php(54): Magento\Eav\Model\Validator\Attribute\Data->isValid(Object(Magento\Customer\Model\Customer\Interceptor))

3 /var/www/html/vendor/magento/framework/Validator.php(59): Magento\Framework\Validator\Constraint->isValid(Object(Magento\Customer\Model\Customer\Interceptor))

4 /var/www/html/vendor/magento/ in /var/www/html/vendor/magento/module-eav/Model/Attribute/Data/Text.php

on line 141

I did setup:di:compile cache:flush generated deleted but not working.

Can somebody help to find issue please.

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.