Blog

Show Login and Create an Account Form in Popup in Magento2

Do you want to Show Login and Create an Account Form in Popup in Magento2? This is the requirement on most of the Magento2 sites.

I have explained each and every step here. Follow step by step to display Login and Create an Account on the Popup.

The following are the steps:

    • Step 1: Create Module
    • Step 2:  Add the class to the link “Sign In” or “Create an Account” present on the top header
    • Step 3: Controller for Processing Ajax Request for Create an Account
    • Step 4: Create frontname for the URL
    • Step 5:  Reload the sections named “checkout-data”, “cart”, “customer”
    • Step 6: Create Blocks for Login and Register
    • Step 7: Create customer-authentication-popup.js to show popup of Login and Register
    • Step 8: Deploy the changes

Let’s start the process…

Step 1: Create Module

Create file registration.php at app/code/Thecoachsmb/Customer

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Thecoachsmb_Customer',
    __DIR__
);

Create module.xml file at app/code/Thecoachsmb/Customer/etc/ 

Step 2:  Add the class to the link “Sign In” or “Create an Account” present on the top header.

Create default.xml file in app/code/Thecoachsmb/Customer/view/frontend/layout

with the following content:-

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
   <body>
      <referenceBlock name="register-link">
          <arguments>
               <argument name="class" xsi:type="string">customer-register-link</argument>
          </arguments>
      </referenceBlock>
      <referenceBlock name="authorization-link-login">
          <arguments>
              <argument name="class" xsi:type="string">customer-login-link</argument>
          </arguments>
      </referenceBlock>
      <referenceContainer name="before.body.end">
           <block class="Thecoachsmb\Customer\Block\Form\Login" name="customer-popup-login" template="Thecoachsmb_Customer::login.phtml" />
           <block class="Thecoachsmb\Customer\Block\Form\Register" name="customer-popup-register" template="Thecoachsmb_Customer::register.phtml" />
      </referenceContainer>
   </body>
</page>

Step 3: Controller for Processing Ajax Request for Create an Account

Create Register.php file app/code/Thecoachsmb/Customer/Controller/Customer/Ajax/

<?php
namespace Thecoachsmb\Customer\Controller\Customer\Ajax;

use Magento\Framework\Exception\StateException;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Customer\Helper\Address;
use Magento\Customer\Model\Account\Redirect;
use Magento\Framework\App\ObjectManager;
use Magento\Customer\Api\AccountManagementInterface;

class Register extends \Magento\Framework\App\Action\Action
{
/**
* @var \Magento\Framework\Controller\Result\JsonFactory
*/
protected $resultJsonFactory;

/**
* @var \Magento\Framework\Controller\Result\RawFactory
*/
protected $resultRawFactory;

/**
* @var \Magento\Customer\Model\Session
*/
protected $session;

/**
* @var \Magento\Customer\Model\Registration
*/
protected $registration;

/**
* @var \Magento\Framework\Data\Form\FormKey\Validator
*/
protected $formKeyValidator;

/**
* @var \Magento\Customer\Model\CustomerExtractor
*/
protected $customerExtractor;

/**
* @var \Magento\Customer\Api\AccountManagementInterface
*/
protected $accountManagement;

/**
* @var \Magento\Newsletter\Model\SubscriberFactory
*/
protected $subscriberFactory;

/**
* @var \Magento\Customer\Model\Url
*/
protected $customerUrl;

/**
* @var \Magento\Customer\Helper\Address
*/
protected $addressHelper;

/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;

/**
* @var \Magento\Customer\Model\Account\Redirect
*/
protected $accountRedirect;

/**
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
protected $scopeConfig;

/**
* @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
*/
protected $cookieMetadataFactory;

/**
* @var \Magento\Framework\Stdlib\Cookie\PhpCookieManager
*/
protected $cookieMetadataManager;

/**
* @var \Magento\Framework\Escaper
*/
protected $escaper;

/**
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
* @param \Magento\Framework\Controller\Result\RawFactory $resultRawFactory
* @param \Magento\Customer\Model\Session $customerSession
* @param \Magento\Customer\Model\Registration $customerRegistration
* @param \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator
* @param \Magento\Customer\Api\AccountManagementInterface $accountManagement
* @param \Magento\Customer\Model\CustomerExtractor $customerExtractor
* @param \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
* @param \Magento\Customer\Model\Url $customerUrl
* @param \Magento\Framework\UrlInterface $urlModel
* @param \Magento\Customer\Helper\Address $addressHelper
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Customer\Model\Account\Redirect $accountRedirect
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
* @param \Magento\Framework\Escaper $escaper
* @param \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory
* @param \Magento\Framework\Stdlib\Cookie\PhpCookieManager $cookieMetadataManager
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
\Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
\Magento\Customer\Model\Session $customerSession,
\Magento\Customer\Model\Registration $customerRegistration,
\Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator,
\Magento\Customer\Api\AccountManagementInterface $accountManagement,
\Magento\Customer\Model\CustomerExtractor $customerExtractor,
\Magento\Newsletter\Model\SubscriberFactory $subscriberFactory,
\Magento\Customer\Model\Url $customerUrl,
\Magento\Framework\UrlInterface $urlModel,
\Magento\Customer\Helper\Address $addressHelper,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Customer\Model\Account\Redirect $accountRedirect,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Framework\Escaper $escaper,
\Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory,
\Magento\Framework\Stdlib\Cookie\PhpCookieManager $cookieMetadataManager
) {
parent::__construct($context);
$this->resultJsonFactory = $resultJsonFactory;
$this->resultRawFactory = $resultRawFactory;
$this->session = $customerSession;
$this->registration = $customerRegistration;
$this->formKeyValidator = $formKeyValidator;
$this->accountManagement = $accountManagement;
$this->customerExtractor = $customerExtractor;
$this->subscriberFactory = $subscriberFactory;
$this->customerUrl = $customerUrl;
$this->urlModel = $urlModel;
$this->addressHelper = $addressHelper;
$this->storeManager = $storeManager;
$this->accountRedirect = $accountRedirect;
$this->scopeConfig = $scopeConfig;
$this->escaper = $escaper;
}

/**
* Retrieve cookie manager
*
* @deprecated 100.1.0
* @return \Magento\Framework\Stdlib\Cookie\PhpCookieManager
*/
private function getCookieManager()
{
if (!$this->cookieMetadataManager) {
$this->cookieMetadataManager = ObjectManager::getInstance()->get(
\Magento\Framework\Stdlib\Cookie\PhpCookieManager::class
);
}
return $this->cookieMetadataManager;
}

/**
* Retrieve cookie metadata factory
*
* @deprecated 100.1.0
* @return \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
*/
private function getCookieMetadataFactory()
{
if (!$this->cookieMetadataFactory) {
$this->cookieMetadataFactory = ObjectManager::getInstance()->get(
\Magento\Framework\Stdlib\Cookie\CookieMetadataFactory::class
);
}
return $this->cookieMetadataFactory;
}

/**
* @return \Magento\Framework\Controller\ResultInterface
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function execute()
{
$credentials = null;
$httpBadRequestCode = 400;

/** @var \Magento\Framework\Controller\Result\Raw $resultRaw */
$resultRaw = $this->resultRawFactory->create();
if ($this->getRequest()->getMethod() !== 'POST' || !$this->getRequest()->isXmlHttpRequest()) {
return $resultRaw->setHttpResponseCode($httpBadRequestCode);
}

$formKeyValidation = $this->formKeyValidator->validate($this->getRequest());

$response = [
'errors' => false,
'message' => __('Login successful.')
];

if ($this->session->isLoggedIn()) {
$response = [
'errors' => false,
'message' => __('You are already logged in.')
];
} elseif (!$this->registration->isAllowed()) {
$response = [
'errors' => true,
'message' => __('Customer registration is already disabled.')
];
} elseif (!$formKeyValidation) {
$response = [
'errors' => true,
'message' => $this->getRequest()->getParam('password')
];
} else {
$this->session->regenerateId();
try {
$customer = $this->customerExtractor->extract('customer_account_create', $this->_request);

$password = $this->getRequest()->getParam('password');
$confirmation = $this->getRequest()->getParam('password_confirmation');

$this->checkPasswordConfirmation($password, $confirmation);

$customer = $this->accountManagement
->createAccount($customer, $password);

if ($this->getRequest()->getParam('is_subscribed', false)) {
$this->subscriberFactory->create()->subscribeCustomerById($customer->getId());
}

$this->_eventManager->dispatch(
'customer_register_success',
['account_controller' => $this, 'customer' => $customer]
);

$confirmationStatus = $this->accountManagement->getConfirmationStatus($customer->getId());
if ($confirmationStatus === AccountManagementInterface::ACCOUNT_CONFIRMATION_REQUIRED) {
$email = $this->customerUrl->getEmailConfirmationUrl($customer->getEmail());
$response = [
'errors' => true,
'message' => __(
'You must confirm your account. Please check your email for the confirmation link or <a href="%1">click here</a> for a new link.',
$email
)
];
} else {
$this->session->setCustomerDataAsLoggedIn($customer);
$response = [
'errors' => false,
'message' => $this->getSuccessMessage()
];
$requestedRedirect = $this->accountRedirect->getRedirectCookie();
if (!$this->scopeConfig->getValue('customer/startup/redirect_dashboard') && $requestedRedirect) {
$response['redirectUrl'] = $this->_redirect->success($requestedRedirect);
$this->accountRedirect->clearRedirectCookie();
}
}
if ($this->getCookieManager()->getCookie('mage-cache-sessid')) {
$metadata = $this->getCookieMetadataFactory()->createCookieMetadata();
$metadata->setPath('/');
$this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata);
}
} catch (StateException $e) {
$url = $this->_url->getUrl('customer/account/forgotpassword');
$response = [
'errors' => true,
'message' => __(
'There is already an account with this email address. If you are sure that it is your email address, <a href="%1">click here</a> to get your password and access your account.',
$url
)
];
} catch (InputException $e) {
$response = [
'errors' => true,
'message' => $this->escaper->escapeHtml($e->getMessage())
];
} catch (LocalizedException $e) {
$response = [
'errors' => true,
'message' => $this->escaper->escapeHtml($e->getMessage())
];
} catch (\Exception $e) {
$response = [
'errors' => true,
'message' => __('We can\'t save the customer.')
];
}

$this->session->setCustomerFormData($this->getRequest()->getPostValue());
}

/** @var \Magento\Framework\Controller\Result\Json $resultJson */
$resultJson = $this->resultJsonFactory->create();
return $resultJson->setData($response);
}

/**
* Make sure that password and password confirmation matched
*
* @param string $password
* @param string $confirmation
* @return void
* @throws InputException
*/
protected function checkPasswordConfirmation($password, $confirmation)
{
if ($password != $confirmation) {
throw new InputException(__('Please make sure your passwords match.'));
}
}

/**
* Retrieve success message
*
* @return string
*/
protected function getSuccessMessage()
{
if ($this->addressHelper->isVatValidationEnabled()) {
if ($this->addressHelper->getTaxCalculationAddressType() == Address::TYPE_SHIPPING) {
// @codingStandardsIgnoreStart
$message = __(
'If you are a registered VAT customer, please <a href="%1">click here</a> to enter your shipping address for proper VAT calculation.',
$this->_url->getUrl('customer/address/edit')
);
// @codingStandardsIgnoreEnd
} else {
// @codingStandardsIgnoreStart
$message = __(
'If you are a registered VAT customer, please <a href="%1">click here</a> to enter your billing address for proper VAT calculation.',
$this->_url->getUrl('customer/address/edit')
);
// @codingStandardsIgnoreEnd
}
} else {
$message = __('Thank you for registering with %1.', $this->storeManager->getStore()->getFrontendName());
}
return $message;
}
}

Step 4: Create frontname for the URL

Define the new frontend route name for this module. Create the new file named routes.xml in the path app\code\Thecoachsmb\Customer\etc\frontend\.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
   <router id="standard">
      <route id="coachcustomer" frontName="coachcustomer">
         <module name="Thecoachsmb_Customer"/>
      </route>
    </router>
</config>

Step 5:  Reload the sections named “checkout-data”, “cart”, “customer”

Create the new file named sections.xml in the path app\code\Thecoachsmb\Customer\etc\frontend\.

This step helps us to reload the sections named “checkout-data”, “cart”, “customer”, whenever the actions named “coachcustomer/customer_ajax/register” and “customer/ajax/login” called by Ajax.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
    <action name="coachcustomer/customer_ajax/register">
        <section name="checkout-data"/>
        <section name="cart"/>
        <section name="customer"/>
    </action>
    <action name="customer/ajax/login">
        <section name="checkout-data"/>
        <section name="cart"/>
        <section name="customer"/>
    </action>
</config>

Step 6: Create Blocks for Login and Register

Create Login.php file in app\code\Thecoachsmb\Customer\Block\Form\

with the content:

<?php

namespace Thecoachsmb\Customer\Block\Form;

class Login extends \Magento\Framework\View\Element\Template
{
/**
* @var \Magento\Customer\Model\Session
*/
protected $customerSession;

/**
* @var \Magento\Framework\App\Http\Context
*/
protected $httpContext;

/**
* Registration
*
* @var \Magento\Customer\Model\Registration
*/
protected $registration;

/**
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Customer\Model\Session $customerSession
* @param \Magento\Framework\App\Http\Context $httpContext
* @param \Magento\Customer\Model\Registration $registration
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Customer\Model\Session $customerSession,
\Magento\Framework\App\Http\Context $httpContext,
\Magento\Customer\Model\Registration $registration,
array $data = []
) {
parent::__construct($context, $data);
$this->customerSession = $customerSession;
$this->httpContext = $httpContext;
$this->registration = $registration;
}

/**
* Return registration
*
* @return \Magento\Customer\Model\Registration
*/
public function getRegistration()
{
return $this->registration;
}

/**
* Retrieve form posting url
*
* @return string
*/
public function getPostActionUrl()
{
return $this->getUrl('customer/ajax/login');
}

/**
* Check if autocomplete is disabled on storefront
*
* @return bool
*/
public function isAutocompleteDisabled()
{
return (bool)!$this->_scopeConfig->getValue(
\Magento\Customer\Model\Form::XML_PATH_ENABLE_AUTOCOMPLETE,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
}

/**
* Checking customer login status
*
* @return bool
*/
public function customerIsAlreadyLoggedIn()
{
return (bool)$this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
}

/**
* Retrieve registering URL
*
* @return string
*/
public function getCustomerRegistrationUrl()
{
return $this->getUrl('customer/account/create');
}
}

Create Register.php in app\code\Thecoachsmb\Customer\Block\Form\

<?php

namespace Thecoachsmb\Customer\Block\Form;

use Magento\Customer\Model\AccountManagement;

class Register extends \Magento\Directory\Block\Data
{
/**
* @var \Magento\Customer\Model\Session
*/
protected $customerSession;

/**
* @var \Magento\Framework\Module\Manager
*/
protected $moduleManager;

/**
* @var \Magento\Framework\App\Http\Context
*/
protected $httpContext;

/**
* Registration
*
* @var \Magento\Customer\Model\Registration
*/
protected $registration;

/**
* Constructor
*
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Directory\Helper\Data $directoryHelper
* @param \Magento\Framework\Json\EncoderInterface $jsonEncoder
* @param \Magento\Framework\App\Cache\Type\Config $configCacheType
* @param \Magento\Directory\Model\ResourceModel\Region\CollectionFactory $regionCollectionFactory
* @param \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory
* @param \Magento\Framework\Module\Manager $moduleManager
* @param \Magento\Customer\Model\Session $customerSession
* @param \Magento\Framework\App\Http\Context $httpContext
* @param \Magento\Customer\Model\Registration $registration
* @param array $data
*
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Directory\Helper\Data $directoryHelper,
\Magento\Framework\Json\EncoderInterface $jsonEncoder,
\Magento\Framework\App\Cache\Type\Config $configCacheType,
\Magento\Directory\Model\ResourceModel\Region\CollectionFactory $regionCollectionFactory,
\Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory,
\Magento\Framework\Module\Manager $moduleManager,
\Magento\Customer\Model\Session $customerSession,
\Magento\Customer\Model\Url $customerUrl,
\Magento\Framework\App\Http\Context $httpContext,
\Magento\Customer\Model\Registration $registration,
array $data = []
) {
$this->moduleManager = $moduleManager;
$this->customerSession = $customerSession;
$this->httpContext = $httpContext;
$this->registration = $registration;
parent::__construct(
$context,
$directoryHelper,
$jsonEncoder,
$configCacheType,
$regionCollectionFactory,
$countryCollectionFactory,
$data
);
}

/**
* Return registration
*
* @return \Magento\Customer\Model\Registration
*/
public function getRegistration()
{
return $this->registration;
}

/**
* Retrieve the form posting URL
*
* @return string
*/
public function getPostActionUrl()
{
return $this->getUrl('coachcustomer/customer_ajax/register');
}

/**
* Retrieve back URL
*
* @return string
*/
public function getBackUrl()
{
return $this->getUrl('customer/account/login');
}

/**
* Retrieve form data
*
* @return mixed
*/
public function getFormData()
{
$data = $this->getData('form_data');
if ($data === null) {
$formData = $this->customerSession->getCustomerFormData(true);
$data = new \Magento\Framework\DataObject();
if ($formData) {
$data->addData($formData);
$data->setCustomerData(1);
}
if (isset($data['region_id'])) {
$data['region_id'] = (int)$data['region_id'];
}
$this->setData('form_data', $data);
}
return $data;
}

/**
* Newsletter module availability
*
* @return bool
*/
public function isNewsletterEnabled()
{
return $this->moduleManager->isOutputEnabled('Magento_Newsletter');
}

/**
* Get minimum password length
*
* @return string
*/
public function getMinimumPasswordLength()
{
return $this->_scopeConfig->getValue(AccountManagement::XML_PATH_MINIMUM_PASSWORD_LENGTH);
}

/**
* Get number of password required character classes
*
* @return string
*/
public function getRequiredCharacterClassesNumber()
{
return $this->_scopeConfig->getValue(AccountManagement::XML_PATH_REQUIRED_CHARACTER_CLASSES_NUMBER);
}

/**
* Checking customer login status
*
* @return bool
*/
public function customerIsAlreadyLoggedIn()
{
return (bool)$this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
}
}

Step 6: Display the Form.Create Login form content.

For this, create login.phtml file app\code\Thecoachsmb\Customer\view\frontend\templates\

<?php
/** @var \Thecoachsmb\Customer\Block\Form\Login $block */
?>
<?php if (!$block->customerIsAlreadyLoggedIn()): ?>
<style>
.customer-popup-login {
display: none;
}
.or-another-selection {
display: inline-block;
padding-right: 5px;
}
@media(max-width: 767px) {
.or-another-selection {
display: block;
text-align: center;
margin-bottom: 5px;
}
}
</style>
<div id="customer-popup-login" class="customer-popup-login">
<div class="block block-customer-login">
<div class="block-content" aria-labelledby="block-customer-popup-login-heading">
<form class="form form-login"
action="<?php /* @escapeNotVerified */ echo $block->getPostActionUrl() ?>"
method="post"
id="customer-popup-login-form"
data-mage-init='{"validation":{}}'>
<?php echo $block->getBlockHtml('formkey'); ?>
<input type="hidden" name="redirect_url" value="<?php echo $this->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]); ?>" />
<fieldset class="fieldset login" data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>">
<div class="field note"><?php /* @escapeNotVerified */ echo __('If you have an account, sign in with your email address.') ?></div>
<div class="messages"></div>
<div class="field email required">
<label class="label" for="email"><span><?php /* @escapeNotVerified */ echo __('Email') ?></span></label>
<div class="control">
<input name="username" value="" <?php if ($block->isAutocompleteDisabled()) :?> autocomplete="off"<?php endif; ?> id="email-login" type="email" class="input-text" title="<?php /* @escapeNotVerified */ echo __('Email') ?>" data-validate="{required:true, 'validate-email':true}">
</div>
</div>
<div class="field password required">
<label for="pass" class="label"><span><?php /* @escapeNotVerified */ echo __('Password') ?></span></label>
<div class="control">
<input name="password" type="password" <?php if ($block->isAutocompleteDisabled()) :?> autocomplete="off"<?php endif; ?> class="input-text" id="pass-login" title="<?php /* @escapeNotVerified */ echo __('Password') ?>" data-validate="{required:true}" >
</div>
</div>
<div class="actions-toolbar">
<div class="primary"><button type="submit" class="action login primary" name="send" id="send2-login"><span><?php /* @escapeNotVerified */ echo __('Sign In') ?></span></button></div>
<?php if ($block->getRegistration()->isAllowed()): ?>
<div class="or-another-selection"><?php echo __('or'); ?></div>
<div class="secondary"><a class="action remind" href="<?php /* @escapeNotVerified */ echo $block->getCustomerRegistrationUrl() ?>" id="customer-popup-registration"><span><?php /* @escapeNotVerified */ echo __('Create an Account') ?></span></a></div>
<?php endif; ?>
</div>
</fieldset>
</form>
</div>
</div>
<script type="text/x-magento-init">
{
"#customer-popup-login": {
"Thecoachsmb_Customer/js/action/customer-authentication-popup": {
"popupTitle": "<?php /* @escapeNotVerified */ echo __('Sign In') ?>",
"innerWidth": "400"
}
}
}
</script>
</div>
<?php endif; ?>

Create register.phtml file in app\code\Thecoachsmb\Customer\view\frontend\templates\

<?php
/** @var \Thecoachsmb\Customer\Block\Form\Register $block */
?>
<?php if (!$block->customerIsAlreadyLoggedIn() && $block->getRegistration()->isAllowed()): ?>
<style>
.customer-popup-register {
display: none;
}
</style>
<div id="customer-popup-register" class="customer-popup-register">
<form class="form-create-account" action="<?php /* @escapeNotVerified */ echo $block->getPostActionUrl() ?>" method="post" id="customer-popup-form-register" enctype="multipart/form-data" autocomplete="off" data-mage-init='{"validation":{}}'>
<?php echo $block->getBlockHtml('formkey'); ?>
<input type="hidden" name="redirect_url" value="<?php echo $this->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]); ?>" />
<div class="messages"></div>
<p><?php /* @escapeNotVerified */ echo __('Creating an account has many benefits: check out faster, keep more than one address, track orders and more.') ?></p>
<fieldset class="fieldset create info">
<legend class="legend"><span><?php /* @escapeNotVerified */ echo __('Personal Information') ?></span></legend><br>
<?php echo $block->getLayout()->createBlock('Magento\Customer\Block\Widget\Name')->setObject($block->getFormData())->setForceUseCustomerAttributes(true)->toHtml() ?>
<?php if ($block->isNewsletterEnabled()): ?>
<div class="field choice newsletter">
<input type="checkbox" name="is_subscribed" title="<?php /* @escapeNotVerified */ echo __('Sign Up for Newsletter') ?>" value="1" id="popup-is_subscribed" class="checkbox">
<label for="is_subscribed" class="label"><span><?php /* @escapeNotVerified */ echo __('Sign Up for Newsletter') ?></span></label>
</div>
<?php endif ?>
</fieldset>
<fieldset class="fieldset create account" data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>">
<legend class="legend"><span><?php /* @escapeNotVerified */ echo __('Sign-in Information') ?></span></legend><br>
<div class="field required">
<label for="popup-email_address" class="label"><span><?php /* @escapeNotVerified */ echo __('Email') ?></span></label>
<div class="control">
<input type="email" name="email" autocomplete="email" id="popup-email_address" value="" title="<?php /* @escapeNotVerified */ echo __('Email') ?>" class="input-text" data-validate="{required:true, 'validate-email':true}">
</div>
</div>
<div class="field password required" data-mage-init='{"passwordStrengthIndicator": {}}'>
<label for="password" class="label"><span><?php /* @escapeNotVerified */ echo __('Password') ?></span></label>
<div class="control">
<input type="password" name="password" id="password"
title="<?php /* @escapeNotVerified */ echo __('Password') ?>"
class="input-text"
data-password-min-length="<?php echo $block->escapeHtml($block->getMinimumPasswordLength()) ?>"
data-password-min-character-sets="<?php echo $block->escapeHtml($block->getRequiredCharacterClassesNumber()) ?>"
data-validate="{required:true, 'validate-customer-password':true}"
autocomplete="off">
<div id="password-strength-meter-container" data-role="password-strength-meter" >
<div id="password-strength-meter" class="password-strength-meter">
<?php /* @escapeNotVerified */ echo __('Password Strength'); ?>:
<span id="password-strength-meter-label" data-role="password-strength-meter-label" >
<?php /* @escapeNotVerified */ echo __('No Password'); ?>
</span>
</div>
</div>
</div>
</div>
<div class="field confirmation required">
<label for="password-confirmation" class="label"><span><?php /* @escapeNotVerified */ echo __('Confirm Password') ?></span></label>
<div class="control">
<input type="password" name="password_confirmation" title="<?php /* @escapeNotVerified */ echo __('Confirm Password') ?>" id="password-confirmation" class="input-text" data-validate="{required:true, equalTo:'#password'}" autocomplete="off">
</div>
</div>
</fieldset>
<div class="actions-toolbar">
<div class="primary">
<button type="submit" class="action submit primary" title="<?php /* @escapeNotVerified */ echo __('Create an Account') ?>"><span><?php /* @escapeNotVerified */ echo __('Create an Account') ?></span></button>
</div>
<div class="or-another-selection"><?php echo __('or'); ?></div>
<div class="secondary"><a class="action remind" href="<?php /* @escapeNotVerified */ echo $block->getBackUrl() ?>" id="customer-popup-sign-in"><span><?php /* @escapeNotVerified */ echo __('Sign In') ?></span></a></div>
</div>
</form>
<script type="text/x-magento-init">
{
"#customer-popup-register": {
"Thecoachsmb_Customer/js/action/customer-authentication-popup": {
"popupTitle": "<?php /* @escapeNotVerified */ echo __('Create an Account'); ?>",
"innerWidth": "600"
}
}
}
</script>
</div>
<?php endif; ?>

Step 7: Create customer-authentication-popup.js to show popup of Login and Register

Create customer-authentication-popup.js in app\code\Thecoachsmb\Customer\view\frontend\web\js\action\

with the content:

define([
'jquery',
'Magento_Ui/js/modal/modal',
'Magento_Customer/js/customer-data',
'mage/storage',
'mage/translate',
'mage/mage',
'jquery/ui'
], function ($, modal, customerData, storage, $t) {
'use strict';

$.widget('thecoachsmb.customerAuthenticationPopup', {
options: {
login: '#customer-popup-login',
nextRegister: '#customer-popup-registration',
register: '#customer-popup-register',
prevLogin: '#customer-popup-sign-in'
},

/**
*
* @private
*/
_create: function () {
var self = this,
authentication_options = {
type: 'popup',
responsive: true,
innerScroll: true,
title: this.options.popupTitle,
buttons: false,
modalClass : 'customer-popup'
};

modal(authentication_options, this.element);

// Show the login form in a popup when clicking on the sign in text
$('body').on('click', '.customer-login-link, '+self.options.prevLogin, function() {
$(self.options.register).modal('closeModal');
$(self.options.login).modal('openModal');
self._setStyleCss();
return false;
});

// Show the registration form in a popup when clicking on the create an account text
$('body').on('click', '.customer-register-link, '+self.options.nextRegister, function() {
$(self.options.login).modal('closeModal');
$(self.options.register).modal('openModal');
self._setStyleCss(self.options.innerWidth);
return false;
});

this._ajaxSubmit();
this._resetStyleCss();
},

/**
* Set width of the popup
* @private
*/
_setStyleCss: function(width) {
width = width || 400;
if (window.innerWidth > 786) {
this.element.parent().parent('.modal-inner-wrap').css({'max-width': width+'px'});
}
},

/**
* Reset width of the popup
* @private
*/
_resetStyleCss: function() {
var self = this;
$( window ).resize(function() {
if (window.innerWidth <= 786) {
self.element.parent().parent('.modal-inner-wrap').css({'max-width': 'initial'});
} else {
self._setStyleCss(self.options.innerWidth);
}
});
},

/**
* Submit data by Ajax
* @private
*/
_ajaxSubmit: function() {
var self = this,
form = this.element.find('form'),
inputElement = form.find('input');

inputElement.keyup(function (e) {
self.element.find('.messages').html('');
});

form.submit(function (e) {
if (form.validation('isValid')) {
if (form.hasClass('form-create-account')) {
$.ajax({
url: $(e.target).attr('action'),
data: $(e.target).serializeArray(),
showLoader: true,
type: 'POST',
dataType: 'json',
success: function (response) {
self._showResponse(response, form.find('input[name="redirect_url"]').val());
},
error: function() {
self._showFailingMessage();
}
});
} else {
var submitData = {},
formDataArray = $(e.target).serializeArray();
formDataArray.forEach(function (entry) {
submitData[entry.name] = entry.value;
});
$('body').loader().loader('show');
storage.post(
$(e.target).attr('action'),
JSON.stringify(submitData)
).done(function (response) {
$('body').loader().loader('hide');
self._showResponse(response, form.find('input[name="redirect_url"]').val());
}).fail(function () {
$('body').loader().loader('hide');
self._showFailingMessage();
});
}
}
return false;
});
},

/**
* Display messages on the screen
* @private
*/
_displayMessages: function(className, message) {
$('<div class="message '+className+'"><div>'+message+'</div></div>').appendTo(this.element.find('.messages'));
},

/**
* Showing response results
* @private
* @param {Object} response
* @param {String} locationHref
*/
_showResponse: function(response, locationHref) {
var self = this,
timeout = 800;
this.element.find('.messages').html('');
if (response.errors) {
this._displayMessages('message-error error', response.message);
} else {
this._displayMessages('message-success success', response.message);
}
this.element.find('.messages .message').show();
setTimeout(function() {
if (!response.errors) {
self.element.modal('closeModal');
window.location.href = locationHref;
}
}, timeout);
},

/**
* Show the failing message
* @private
*/
_showFailingMessage: function() {
this.element.find('.messages').html('');
this._displayMessages('message-error error', $t('An error occurred, please try again later.'));
this.element.find('.messages .message').show();
}
});

return $.thecoachsmb.customerAuthenticationPopup;
});

Step 8: Deploy the changes

Final step is the deploy your changes:

  • Remove the folders and files present inside the pub/static/frontend/
  • Remove the folders and files present inside the var/view_preprocessed/pub/static/frontend/
  • Run the below commands:
php bin/magento se:up && php bin/magento se:s:d -f && php bin/magento c:f

Done !!

Follow each and every step carefully. This will display popup for Login and Create an Account Form.

One thought on “Show Login and Create an Account Form in Popup in Magento2

  1. Hello,
    Login-Popup is much easier this way: Just place this one line of code:
    echo $this->getLayout()->createBlock(“Magento\Customer\Block\Form\Login”)->setTemplate(“Magento_Customer::form/login.phtml”)->toHtml();
    into the container of a modal/popup. Thats all.

    For register it works the same way with:
    echo $this->getLayout()->createBlock(“Magento\Customer\Block\Form\Register”)->setTemplate(“Magento_Customer::form/register.phtml”)->toHtml();
    IF you dont use Magento Captcha / MSP reCaptcha. This wont work.
    Will the MSP reCaptcha work in your solution?

    Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *