Hi, My requirement was to add a "subscribe to the newsletter" checkbox at one-page checkout page (below "terms and condition" checkbox). All the things are fine except for 2 issues:
<?php /** * * Register to Newsletter during checkout process */ namespace <Mynamespace>\<Mymodule>\Observer\Sales; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Newsletter\Model\Subscriber; use Magento\Framework\App\RequestInterface; use Psr\Log\LoggerInterface; class OrderPlaceBefore implements ObserverInterface { protected $_subscriber; protected $_request; protected $_logger; /** * @param Subscriber $subscrbr * @param RequestInterface $request * @param LoggerInterface $logger */ public function __construct( Subscriber $subscrbr, RequestInterface $request, LoggerInterface $logger ) { $this->_subscriber = $subscrbr; $this->_request = $request; $this->_logger = $logger; } /** * Subscribe to newsletters if customer checked the checkbox * * @param \Magento\Framework\Event\Observer $observer * @return $this */ public function execute(\Magento\Framework\Event\Observer $observer) { $order = $observer->getEvent()->getOrder(); $customerEmail = $order->getCustomerEmail(); try { **//Here the conditions should go, if the checkbox is checked then only subscribe to newsletter otherwise not //How to get custom checkbox value after order placement? Tried with $this->_request->getpost() but not working, returning an empty array** $subscriber = $this->_subscriber->loadByEmail($customerEmail); if (!$subscriber->getId()) { //at this line, first time for non-existing email, the page is broken, not sure WHY?? $this->_subscriber->subscribe($customerEmail); } } catch (\Exception $e) { $this->_logger->critical($e->getMessage() . ' from Mynamespace-Mymodule ' . $customerEmail); } return $this; } }
Code for Layoutprocessor file
<?php /** * Copyright © Mageside. All rights reserved. * See MS-LICENSE.txt for license details. */ namespace <Mynamespace>\<Mymodule>\Model\Config\Source; use Mageside\SubscribeAtCheckout\Helper\Config as Helper; /** * Class SubscribeLayoutProcessor */ class SubscribeLayoutProcessor { /** * {@inheritdoc} */ public function process($jsLayout) { $jsLayoutSubscribe = [ 'components' => [ 'checkout' => [ 'children' => [ 'steps' => [ 'children' => [ 'billing-step' => [ 'children' => [ 'payment' => [ 'children' => [ 'payments-list' => [ 'children' => [ 'before-place-order' => [ 'children' => [ 'custom_nl_subscribe' => [ 'config' => [ 'checkoutLabel' => 'Subscribe to Newsletter', 'checked' => 1, 'visible' => 1, 'changeable' => 1, 'template' => 'Mageside_SubscribeAtCheckout/form/element/newsletter-subscribe' ], 'component' => 'Magento_Ui/js/form/form', 'displayArea' => 'custom_nl_subscribe', ] ] ] ] ] ] ] ] ] ] ] ] ] ] ]; $jsLayout = array_merge_recursive($jsLayout, $jsLayoutSubscribe); return $jsLayout; } }
Not sure where I am wrong? Can you please guide? Thanks in advance.