In this tutorial, we will learn about how to load additional customer data through knockout JS.
We will create our custom routes and call our custom template. In that, we will load our data by using knockout JS techniques.
Let's start it by creating custom module.
Find the complete module on Github.
Create folder in
app/code/
Magelearn/CustomerLoginStep 1: Create module registration file
Add registration.php file in it:
<?php /** * Copyright © All rights reserved. * See COPYING.txt for license details. */ use Magento\Framework\Component\ComponentRegistrar; ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Magelearn_CustomerLogin', __DIR__);Add composer.json file in it:
{ "name": "magelearn/customerlogin", "description": "Magento2 sample module to load additional customer data through knockout JS", "type": "magento2-module", "license": "OSL-3.0", "authors": [ { "email": "info@mage2gen.com", "name": "Mage2Gen" }, { "email": "vijaymrami@gmail.com", "name": "vijay rami" } ], "minimum-stability": "dev", "require": {}, "autoload": { "files": [ "registration.php" ], "psr-4": { "Magelearn\\CustomerLogin\\": "" } } }
Add etc/module.xml file in it:
<?xml version="1.0" ?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Magelearn_CustomerLogin" setup_version="1.0.0">
</module> </config>
Step 2. Use Plugin Method to add additional Data.
Magelearn/CustomerLogin/etc
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Customer\CustomerData\Customer">
<plugin disabled="false" name="Magelearn_CustomerLogin_Plugin_Magento_Customer_CustomerData_Customer" sortOrder="10" type="Magelearn\CustomerLogin\Plugin\Magento\Customer\CustomerData\Customer"/>
</type>
</config>
Create Customer.php inside Magelearn/CustomerLogin/Plugin/Magento/Customer/CustomerData
Here we used after Plugin method (afterGetSectionData) to load additional customer data.
<?php
namespace Magelearn\CustomerLogin\Plugin\Magento\Customer\CustomerData;
/**
* Class Customer
* @package Magelearn\CustomerLogin\Plugin\Magento\Customer\CustomerData
*/
class Customer
{
/**
* @var \Magento\Customer\Model\Session\Proxy
*/
private $customerSession;
/**
* @var \Magento\Customer\Api\GroupRepositoryInterface
*/
private $groupRepository;
/**
* Customer constructor.
* @param \Magento\Customer\Model\Session\Proxy $customerSession
* @param \Magento\Customer\Api\GroupRepositoryInterface $groupRepository
*/
// phpcs:disable
public function __construct(
\Magento\Customer\Model\Session\Proxy $customerSession,
\Magento\Customer\Api\GroupRepositoryInterface $groupRepository
) {
$this->customerSession = $customerSession;
$this->groupRepository = $groupRepository;
}
// phpcs:enable
/**
* @param \Magento\Customer\CustomerData\Customer $subject
* @param $result
* @return mixed
*/
public function afterGetSectionData(\Magento\Customer\CustomerData\Customer $subject, $result)
{
$result['is_logged_in'] = $this->customerSession->isLoggedIn();
if ($this->customerSession->isLoggedIn() && $this->customerSession->getCustomerId()) {
$customer = $this->customerSession->getCustomer();
$result['email'] = $customer->getEmail();
$result['lastname'] = $customer->getLastname();
$result['customer_group_id'] = $customer->getGroupId();
$result['customer_group_name'] = $this->getGroupName($customer->getGroupId());
}
return $result;
}
/**
* Get group name
* @param $groupId
* @return \Magento\Framework\Phrase|string
*/
public function getGroupName($groupId)
{
try {
$group = $this->groupRepository->getById($groupId);
return $group->getCode();
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
return __("None");
} catch (\Magento\Framework\Exception\LocalizedException $e) {
return __("None");
}
}
}
Step 3. Create custom routes, Block, controller, Layout and template files to display additional Data on frontend.
Create routes.xml inside
Magelearn/CustomerLogin/etc/frontend
Here, We will define our frontend routes.
<?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 frontName="magelearn_customerlogin" id="magelearn_customerlogin">
<module name="Magelearn_CustomerLogin"/>
</route>
</router>
</config>
After defining routes, We will define our frontend controller, block, layout and template files.Create magelearn_customerlogin_index_index.xml file inside Magelearn/CustomerLogin/view/frontend/layout
<?xml version="1.0" ?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="Magelearn\CustomerLogin\Block\Index\Index" name="index.index" template="Magelearn_CustomerLogin::index/index.phtml"/>
</referenceContainer>
</body>
</page>
Create controller Index.php file inside Magelearn/CustomerLogin/Controller/Index
<?php
namespace Magelearn\CustomerLogin\Controller\Index;
/**
* Class Index
* @package Magelearn\CustomerLogin\Controller\Index
*/
class Index extends \Magento\Framework\App\Action\Action
{
/**
* @var \Magento\Framework\View\Result\PageFactory
*/
protected $resultPageFactory;
/**
* Constructor
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory
) {
$this->resultPageFactory = $resultPageFactory;
parent::__construct($context);
}
/**
* Execute view action
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
return $this->resultPageFactory->create();
}
}
Create index.phtml file inside Magelearn/CustomerLogin/view/frontend/templates/index
<div class="greet welcome" data-bind="scope: 'customer'">
<!-- ko if: customer().is_logged_in -->
<span class="logged-in"
data-bind="text: new String('<?= $block->escapeHtml(__('Welcome back %1', '%1')) ?>').replace('%1', customer().firstname)">
</span>
<!-- /ko -->
<!-- ko ifnot: customer().is_logged_in -->
<span class="not-logged-in"
data-bind='html:"<?= $block->escapeHtml(__("Please <a href='%1'>login</a>", $block->getUrl('customer/account/login'))) ?>"'>
</span>
<!-- /ko -->
<!-- ko if: customer().email -->
<div>
<span class="logged-in"
data-bind="text: new String('<?= $block->escapeHtml(__('Email: %1', '%1')) ?>').replace('%1', customer().email)">
</span>
</div>
<!-- /ko -->
<!-- ko if: customer().customer_group_id -->
<div>
<span class="logged-in"
data-bind="text: new String('<?= $block->escapeHtml(__('Customer Group: %1', '%1')) ?>').replace('%1', customer().customer_group_name)">
</span>
</div>
<!-- /ko -->
<!-- ko if: blockIsLoggedIn == '1' -->
<span data-bind="text: new String('<?= $block->escapeHtml(__('According to the block logic you are currently logged In')) ?>')"></span>
<!-- /ko -->
<!-- ko ifnot: blockIsLoggedIn == '1' -->
<span data-bind="text: new String('<?= $block->escapeHtml(__('as according to the block logic you are not currently logged in')) ?>')"></span>
<!-- /ko -->
</div>
<script type="text/x-magento-init">
{
"*": {
"Magento_Ui/js/core/app": {
"components": {
"customer": {
"component": "Magento_Customer/js/view/customer",
"blockIsLoggedIn": "<?= $block->escapeJs($block->isCustomerLoggedIn()); ?>"
}
}
}
}
}
</script>
Create block file Index.php file inside Magelearn/CustomerLogin/Block/Index
<?php
namespace Magelearn\CustomerLogin\Block\Index;
use Magento\Framework\App\Http\Context as CustomerContext;
/**
* Class Index
* @package Magelearn\CustomerLogin\Block\Index
*/
class Index extends \Magento\Framework\View\Element\Template
{
/**
* @var CustomerContext
*/
protected $customerContext;
/**
* Index constructor.
* @param \Magento\Framework\View\Element\Template\Context $context
* @param CustomerContext $customerContext
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
CustomerContext $customerContext,
array $data = []
) {
$this->customerContext = $customerContext;
parent::__construct($context, $data);
}
/**
* Check is Customer Logged In
* @return int
*/
public function isCustomerLoggedIn()
{
$isLoggedIn = $this->customerContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
return (bool) $isLoggedIn ? 1 : 0;
}
}
That's it. Now got to the URL /magelearn_customerlogin you can see the below details if you are logged in into the site.
0 Comments On "Sample Module to load additional customer data through knockout JS Magento2"