I need to integrate a functionality where when a user clicks add to cart it should check whether he is a logged in customer or not. If he is a logged in customer the product should be added in cart. Else it should redirect to Login page after logging in the products to be added automatically. If anyone has any idea pls share.
2 Answers
- listen to the event
sales_quote_add_item
- check if the customer is logged in
- if not, rdirect to login page
Method 1:
You need to create an observer (controller_action_predispatch_checkout_cart_add
) to check the customer is logged in or not. If not, you need to redirect to login page.
Example: redirect to login page from the observer, add the customer login check logic from here.
<?php
namespace Vendor\ModuleName\Observer;
use Magento\Framework\Event\ObserverInterface;
class CheckLoginObserver implements ObserverInterface
{
protected $redirect;
public function __construct(
\Magento\Framework\App\Response\RedirectInterface $redirect
) {
$this->redirect = $redirect;
}
/**
* Redirect to login page
*
* @param \Magento\Framework\Event\Observer $observer
* @return $this
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
/** @var \Magento\Framework\App\Action\Action $controller */
$controller = $observer->getControllerAction();
$this->redirect->redirect($controller->getResponse(), 'customer/account/login');
return $this;
}
}
Method 2:
If you want to change globally including API request, you need to add before plugin for Magento\Checkout\Model\Cart:addProduct($productInfo, $requestInfo = null)
and repeat the same thing what you did in the observer.