0

I have a simple code, where i add a simple product to the cart

$cart = $obj->get('\Magento\Checkout\Model\Cart');
$cart->addProduct(5, 3);
$cart->save();

but the last row, returns this error: Fatal error: Uncaught Magento\Framework\Exception\StateException: Shipping address is not set

Why is necessary to add a shipping address to save the cart?

How i can add an address programmatically?

0

\Magento\Checkout\Model\Cart' class has been deprecated from100.1.0`.

Use \Magento\Quote\Model\Quoteinstead Please check https://github.com/magento/magento2/commit/e5479b4e7b87b8ad22dc1ca8e4c33556999da5f2

0

You can add shipping address programmatically by following code..!

=> event.xml

    <?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_quote_save_after">
            <observer name="sales_quote_save_after_event" instance="Test\Module\Observer\SalesQuoteSaveAfter" />
        </event>
    </config>

=> Test/Module/Observer/SalesQuoteSaveAfter.php

    <?php

    namespace Test\Module\Observer;

    use Magento\Framework\Event\ObserverInterface;

    class SalesQuoteSaveAfter implements ObserverInterface
    {
        protected $addressFactory;

        public function __construct(\Magento\Quote\Api\Data\AddressInterface $address) 
        {
            $this->address = $address;
        }

        public function execute(\Magento\Framework\Event\Observer $observer)
        {
            $quote = $observer->getEvent()->getQuote();

            if (!$quote->hasItems()) 
            {
                $quote->setBillingAddress($this->getEmptyAddress())->setShippingAddress($this->getEmptyAddress());
            }
        }

        private function getEmptyAddress() 
        {
            $this->address->setRegionId(0);
            $this->address->setRegion("");
            $this->address->setRegionCode("");
            $this->address->setCountryId("");
            $this->address->setStreet([""]);
            $this->address->setCompany("");
            $this->address->setTelephone("");
            $this->address->setFax("");
            $this->address->setPostcode("");
            $this->address->setCity("");
            $this->address->setFirstname("");
            $this->address->setLastname("");
            $this->address->setMiddlename("");
            $this->address->setEmail("");
            $this->address->setSameAsBilling(1);
            $this->address->setSaveInAddressBook(0);
            return $this->address;
        }
    }

Your Answer

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

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