Skip to content

Instantly share code, notes, and snippets.

@DimaKriuchko
Last active April 12, 2021 09:44
Show Gist options
  • Select an option

  • Save DimaKriuchko/bb5f958eddd4e64586d6b628462539f8 to your computer and use it in GitHub Desktop.

Select an option

Save DimaKriuchko/bb5f958eddd4e64586d6b628462539f8 to your computer and use it in GitHub Desktop.
\!h events.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="customer_login">
<observer name="custom_customer_login" instance="\Vendor\Module\Observer\CustomerLogin" />
</event>
</config>
\!h CustomerLogin.php
<?php
namespace Vendor\Module\Observer;
use Magento\Framework\Event\ObserverInterface;
class CustomerLogin implements ObserverInterface
{
protected $_url;
protected $_session;
protected $messageManager;
protected $modelCart;
protected $modelProductFactory;
public function __construct(
\Magento\Customer\Model\Session $session,
\Magento\Framework\Message\ManagerInterface $messageManager,
\Magento\Framework\UrlInterface $url,
\Magento\Checkout\Model\Cart $modelCart,
\Magento\Catalog\Model\ProductFactory $modelProductFactory
) {
$this->_session = $session;
$this->messageManager = $messageManager;
$this->_url = $url;
$this->modelCart = $modelCart;
$this->modelProductFactory = $modelProductFactory;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$productID = 1;
$buyRequest = array(
'product' => $productID,
'qty' => '4'
);
$product = $this->modelProductFactory->create()->load($productID);
$cart = $this->modelCart;
$cart->addProduct($product, $buyRequest);
$cart->getQuote()->setTotalsCollectedFlag(false);
$cart->save();
$CustomRedirectionUrl = $this->_url->getUrl('checkout/cart');
$this->_session->setBeforeAuthUrl($CustomRedirectionUrl);
$this->messageManager->addSuccess($product->getName());
exit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment