1

I am trying to create a free order with code, it all works up until adding a shipping address and method, it crashes with errors instead of creating the quote and i can't see why as the code looks fine to me.

Billing address is no problem. I'm just going to provide a small section of the code relating to shipping address:

// add shipping address
            /** @var Address $shippingAddress */
            $shippingAddress = $this->_addressFactory->create();
            $shippingAddress->addData([
                'firstname' => (string)$order->Shipping->FirstName,
                'middlename' => (string)$order->Shipping->MiddleName,
                'lastname' => (string)$order->Shipping->LastName,
                'street' => [(string)$order->Shipping->Street],
                'city' => (string)$order->Shipping->City,
                'postcode' => (string)$order->Shipping->PostCode,
                'telephone' => (string)$order->Shipping->Telephone,
                'country_id' => (string)$order->Shipping->Country,
                'region' => (string)$order->Shipping->Region
            ]);

            $shippingAddress->setCollectShippingRates(true)
                ->collectShippingRates()
                ->setShippingMethod('freeshipping_freeshipping');

            $quote->setShippingAddress($shippingAddress);

            // add billing address
            /** @var Address $billingAddress */
            $billingAddress = $this->_addressFactory->create();
            $billingAddress->addData([
                'firstname' => (string)$order->Billing->FirstName,
                'middlename' => (string)$order->Billing->MiddleName,
                'lastname' => (string)$order->Billing->LastName,
                'street' => [(string)$order->Billing->Street],
                'city' => (string)$order->Billing->City,
                'postcode' => (string)$order->Billing->PostCode,
                'telephone' => (string)$order->Billing->Telephone,
                'country_id' => (string)$order->Billing->Country,
                'region' => (string)$order->Billing->Region
            ]);

            $quote->setBillingAddress($billingAddress);



             // collect all totals
             $quote->collectTotals();

             //$quote->getPayment()->setMethod('free');

            // save the quote
            $this->_cartRepo->save($quote);

this gives me an error:

Call to a member function getStoreId() on null#0 /vendor/magento/module-quote/Model/Quote/Address.php(1004): Magento\Quote\Model\Quote\Address->requestShippingRates()

It seems to be this line in Address.php:

$storeId = $this->getQuote()->getStoreId() ?: $this->storeManager->getStore()->getId();
1
  • If you need whole working code i will provide you that too.
    – Kareem k
    Commented Jul 9 at 5:19

2 Answers 2

0

change above code to this will fix your issue,as it is tested

$quote->getShippingAddress()->addData([
                'firstname' => (string)$order->Shipping->FirstName,
                'middlename' => (string)$order->Shipping->MiddleName,
                'lastname' => (string)$order->Shipping->LastName,
                'street' => [(string)$order->Shipping->Street],
                'city' => (string)$order->Shipping->City,
                'postcode' => (string)$order->Shipping->PostCode,
                'telephone' => (string)$order->Shipping->Telephone,
                'country_id' => (string)$order->Shipping->Country,
                'region' => (string)$order->Shipping->Region
            ]);
    $quote->getShippingAddress()->setCollectShippingRates(true)
                ->collectShippingRates()
                ->setShippingMethod('freeshipping_freeshipping');
               
            $quote->setPaymentMethod('pay_cash'); //payment method
            $quote->setInventoryProcessed(false); //not effect inventory
            $quote->save();

    
$quote->getBillingAddress()->addData([
                'firstname' => (string)$order->Billing->FirstName,
                'middlename' => (string)$order->Billing->MiddleName,
                'lastname' => (string)$order->Billing->LastName,
                'street' => [(string)$order->Billing->Street],
                'city' => (string)$order->Billing->City,
                'postcode' => (string)$order->Billing->PostCode,
                'telephone' => (string)$order->Billing->Telephone,
                'country_id' => (string)$order->Billing->Country,
                'region' => (string)$order->Billing->Region
            ]);
0

Use the following data to create a quote and order:

<?php
$order = [
    'currency_id' => 'USD',
    'email' => '[email protected]',
    'shipping_address' => ['firstname' => 'John',
        'lastname' => 'Doe',
        'street' => 'xxxxxx',
        'city' => 'xxxxxxx',
        'country_id' => 'US',
        'region' => 'xxxxx',
        'postcode' => '85001',
        'telephone' => '52556542',
        'fax' => '3242322556',
        'save_in_address_book' => 1],
    'items' => [
        ['product_id' => '1', 'qty' => 1],
        ['product_id' => '2', 'qty' => 2]]
    ];
?>

The order create function in the module helper file is as follows:

<?php
namespaceYourNameSpace\ModuleName\Helper;

use Magento\Framework\App\Helper\AbstractHelper;

class Data extends AbstractHelper
{
    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);
    }

    public function createOrder($order)
    {
        $store = $this->storeManager->getStore();
        $websiteId = $this->storeManager->getStore()->getWebsiteId();
        $customer = $this->customerFactory->create();
        $customer->setWebsiteId($websiteId);
        $customer->loadByEmail($order['email']); // load customet by email address
       if (!$customer->getEntityId()) {
            //If not avilable then create this customer
           $customer->setWebsiteId($websiteId)->setStore($store)->setFirstname($order['shipping_address']['firstname'])->setLastname($order['shipping_address']['lastname'])->setEmail($order['email'])->setPassword($order['email']);
            $customer->save();
        }
        $quote = $this->quote->create(); // Create Quote Object
       $quote->setStore($store); // Set Store
       $customer = $this->customerRepository->getById($customer->getEntityId());
        $quote->setCurrency();
        $quote->assignCustomer($customer); // Assign quote to Customer

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

        $quote->getBillingAddress()->addData($order['shipping_address']);
        $quote->getShippingAddress()->addData($order['shipping_address']);

        // Collect Rates and Set Shipping & Payment Method

       $shippingAddress = $quote->getShippingAddress();
        $shippingAddress->setCollectShippingRates(true)->collectShippingRates()->setShippingMethod('freeshipping_freeshipping');
        $quote->setPaymentMethod('checkmo');
        $quote->setInventoryProcessed(false);
        $quote->save();

        // Set Sales Order Payment
       $quote->getPayment()->importData(['method' => 'checkmo']);

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

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

        $orderdata->setEmailSent(0);
        $increment_id = $order->getRealOrderId();
        if ($orderdata->getEntityId()) {
            $result['order_id'] = $orderdata->getRealOrderId();
        } else {
            $result = ['error' => 1, 'msg' => 'Your custom message'];
        }
        return $result;
    }
}
?>

Get all your queries solved. Thank You!

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.