We found the default documentation about adding a new input field to the checkout. https://devdocs.magento.com/guides/v2.3/howdoi/checkout/checkout_form.html
But we can not find any documentation about saving this input value into the session of the customer, so that on page refresh that value is saved until the order is placed.
How can we achieve that?
-
are you able to add more infos? where in the checkout is the custom field? do you have code to share to see what you have at this point?Herve Tribouilloy– Herve Tribouilloy2022年08月23日 10:27:37 +00:00Commented Aug 23, 2022 at 10:27
-
@HerveTribouilloy Thanks! It's displayed on both Shipping and Billing address forms. We created it using the devdocs, to insert only a input text field.JGeer– JGeer2022年08月23日 14:04:04 +00:00Commented Aug 23, 2022 at 14:04
1 Answer 1
You can achieve that by using Event/Observer as we did in one of our Modules.
Create an event.xml file in etc folder as below. You can use any other event on checkout. I am using sales_order_payment_save_before.
<event name="sales_order_payment_save_before">
<observer name="handle_order_attrs" instance="Vendor\Module\Observer\HandleOrderAttrs" />
</event>
Now we have to create an Observer. Create HandleOrderAttrs.php in Vendor/Module/Observer. In this file you can get the order data and save it in Customer Session.
<?php
namespace Vendor\Module\Observer;
use \Magento\Framework\Event\ObserverInterface;
use \Magento\Framework\Event\Observer as EventObserver;
use \Magento\Customer\Model\Session as CustomerSession
use \Magento\Checkout\Model\Session as CheckoutSession;
class HandleOrderAttrs implements ObserverInterface
{
protected $customerSession;
protected $_inputParamsResolver;
protected $_quoteRepository;
protected $checkoutSession;
public function __construct(\Magento\Webapi\Controller\Rest\InputParamsResolver $inputParamsResolver,
\Magento\Quote\Model\QuoteRepository $quoteRepository,
CustomerSession $customerSession,
CheckoutSession $checkoutSession)
{
$this->_inputParamsResolver = $inputParamsResolver;
$this->_quoteRepository = $quoteRepository;
$this->customerSession = $customerSession;
$this->checkoutSession = $checkoutSession;
}
public function execute(EventObserver $observer)
{
$order = $observer->getOrder();
$quoteRepository = $this->_objectManager->create('Magento\Quote\Model\QuoteRepository');
/** @var \Magento\Quote\Model\Quote $quote */
$quote = $quoteRepository->get($order->getQuoteId());
$order->setSampleText( $quote->getSampleText() ); // Similarlly you can get other order data like this
// Save this in Customer Session
$myArray = array('value1','value2');
$setValue = $this->customerSession->setMyValue($myArray); //set value in customer session
// To Save data in Checkout Session Follow this
$this->checkoutSession->setCustomerData($myArray);
$this->checkoutSession->setAnyVar("Hello There"); // You can get it the same way in success page - $this->checkoutSession->getAnyVar();
return $this;
}
}