0

I create a login popup template, only extending the phtml file and moving the xml block in my popup panel. It works fine, but when the user make some error (e.g. wrong the password) I want to redirect on the home page and open the panel with the error message.

I don't know how to do this, because by default magento redirect the user on customer login page.

0

I found the solution, I wrote my controller that extend \Magento\Customer\Controller\Account\LoginPost this is my controller:

class LoginPost extends \Magento\Customer\Controller\Account\LoginPost {
/**
 * @param Context $context
 * @param Session $customerSession
 * @param AccountManagementInterface $customerAccountManagement
 * @param CustomerUrl $customerHelperData
 * @param Validator $formKeyValidator
 * @param AccountRedirect $accountRedirect
 */
public function __construct(
    Context $context,
    Session $customerSession,
    AccountManagementInterface $customerAccountManagement,
    CustomerUrl $customerHelperData,
    Validator $formKeyValidator,
    AccountRedirect $accountRedirect
) {
    parent::__construct($context,
        $customerSession,
        $customerAccountManagement,
        $customerHelperData,
        $formKeyValidator,
        $accountRedirect);
}

/**
 * Login post action
 *
 * @return \Magento\Framework\Controller\Result\Redirect
 * @SuppressWarnings(PHPMD.CyclomaticComplexity)
 */
public function execute()
{
    if ($this->session->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) {
        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        $resultRedirect->setPath('*/*/');
        return $resultRedirect;
    }

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $baseUrl = $objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore()->getBaseUrl();
    $refererUrl = explode('?', $this->_redirect->getRefererUrl())[0];
    $previusPageNoError = str_replace($baseUrl, '', $refererUrl);
    $previusPage = $previusPageNoError . '?error=1';

    if ($this->getRequest()->isPost()) {
        $login = $this->getRequest()->getPost('login');
        if (!empty($login['username']) && !empty($login['password'])) {
            try {
                $customer = $this->customerAccountManagement->authenticate($login['username'], $login['password']);
                $this->session->setCustomerDataAsLoggedIn($customer);
                $this->session->regenerateId();
                if (isset($login['productId'])){
                    $this->addItemToWishlist($login['productId'], $this->session->getCustomer()->getId());
                    $wishListIndex = 'wishlist';
                }
            } catch (EmailNotConfirmedException $e) {
                $value = $this->customerUrl->getEmailConfirmationUrl($login['username']);
                $message = __(
                    'This account is not confirmed.' .
                    ' <a href="%1">Click here</a> to resend confirmation email.',
                    $value
                );
                $this->messageManager->addErrorMessage($message);
                $this->session->setUsername($login['username']);
                return $this->_redirect($previusPage);
            } catch (AuthenticationException $e) {
                $message = __('Invalid login or password.');
                $this->messageManager->addErrorMessage($message);
                $this->session->setUsername($login['username']);
                return $this->_redirect($previusPage);
            } catch (\Exception $e) {
                $this->messageManager->addErrorMessage(__('Invalid login or password.'));
                return $this->_redirect($previusPage);
            }
        } else {
            $this->messageManager->addErrorMessage(__('A login and a password are required.'));
            return $this->_redirect($previusPage);
        }
    }

    if ($previusPageNoError === 'checkout/') {
        return $this->_redirect($previusPageNoError);
    } elseif (isset($wishListIndex)) {
        return $this->_redirect($wishListIndex);
    } else {
        return $this->accountRedirect->getRedirect();
    }
}

private function addItemToWishlist($idProduct, $customerId)
{
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $wishlist = $objectManager->create('Magento\Wishlist\Model\Wishlist');
    $wishlist->loadByCustomerId($customerId, true);
    $wishlist->addNewItem($idProduct);
    $wishlist->save();
}}

Now in my phtml I only need to check with jquery if the url path contain ?error=1 and open the popup.

This is my phtml:

<script type="text/javascript">

require(['jquery', 'jquery/ui'], function ($) {

    function getUrlParameter(sParam) {
        var sPageURL = decodeURIComponent(window.location.search.substring(1)),
            sURLVariables = sPageURL.split('&'),
            sParameterName,
            i;

        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');

            if (sParameterName[0] === sParam) {
                return sParameterName[0] === undefined ? true : sParameterName[0];
            }
        }
    }

    if (getUrlParameter('error') == 'error') {
       // open your login popup 
    }

});</script>

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.