Contents
In this article, I will show you how to update custom attribute data for the customer, we will catch the event to show the last time logged in of the customers through a custom attribute. The aim of this guide is to help you understand how Events – Observer works and how to use them correctly.
Understand catching an event
You have to catch your event by creating events.xml file in your module. There are 3 areas you can put your configuration file in:
- Admin area: App/code/rootfolder/modulename/etc/adminhtml/events.xml
- Frontend area: App/code/rootfolder/modulename/etc/frontend/events.xml
- Global: App/code/rootfolder/modulename/etc/events.xml
In this example, I will put the configuration file under App/code/rootfolder/modulename/etc/adminhtml/events.xml because we will only work with the admin area. Below are the detailed steps.
Step 1: Create Attribute Last Login
Firstly, you have to create the attribute Last Login
<?php
namespace Magepow\Lastlogin\Setup;
use Magento\Eav\Model\Entity;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Eav\Model\Config;
class UpgradeData implements UpgradeDataInterface
{
private $eavSetupFactory;
public function __construct(EavSetupFactory $eavSetupFactory,Config $eavConfig)
{
$this->eavSetupFactory = $eavSetupFactory;
$this->eavConfig = $eavConfig;
}
/**
* @param ModuleDataSetupInterface $setup
* @param ModuleContextInterface $context
*/
public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$setup->startSetup();
if (version_compare($context->getVersion(),'2.6.0','<')){
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
// $attributeCode = 'last_login_at';
// add/update frontend_model to the attribute
$eavSetup->addAttribute(
\Magento\Customer\Model\Customer::ENTITY, // customer entity code
'last_login_at',
[
'label' =>"Last Login",
'type' => 'datetime',
'input' => 'date',
'frontend' => \Magento\Eav\Model\Entity\Attribute\Frontend\Datetime::class,
'backend' => \Magento\Eav\Model\Entity\Attribute\Backend\Datetime::class,
'required' => false,
'user_defined' => true,
'visible' => true,
'system' => false,
'input_filter' => 'date',
'validate_rules' => '{"input_validation":"date"}',
'position' => 999,
]
);
$eavSetup->addAttributeToSet(
\Magento\Customer\Api\CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER,
\Magento\Customer\Api\CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
null,
'last_login_at');
$lastLogin = $this->eavConfig->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'last_login_at');
$lastLogin->setData(
'used_in_forms',
['customer_account_edit','adminhtml_customer','customer_account_create']
);
$lastLogin->save();
}
$setup->endSetup();
}
}
After that, please change the setup_version in file module.xml to make sure they will run for version 2.6.0 of upgrade data.
<?xml version="1.0"?>
<!--
/**
* Copyright © 2016 ExtensionsMall All rights reserved.
* See COPYING.txt for license details.
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Magepow_Lastlogin" setup_version="2.6.0"/>
</config>
Then run php/bin magento setup:upgrade and check your attribute if it’s created on Customers in admin area or eav_attribute in your database.
Step 2: Create event file events.xml
In App/code/Magepow/Lastlogin/etc/adminhtml/events.xml, we have
<?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="magepow_obeserver" instance="Magepow\Lastlogin\Observer\Customerlogin" disable = "false" />
</event>
Step 3: Create Observer class
<?php
namespace Magepow\Lastlogin\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Customer\Model\Customer;
class Customerlogin implements ObserverInterface
{
protected $_customerRepositoryInterface;
public function __construct(\Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface
)
{
$this->_customerRepositoryInterface = $customerRepositoryInterface;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$customer = $observer->getEvent()->getCustomer();
$customerData = $customer->getDataModel();
$customerData->setCustomAttribute('last_login_at', (new \DateTime())->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT));
$customer->updateData($customerData);
$customer->save();
}
}
Step 4: Flush cache and check the result
After flowing 3 steps above, please flush cache in admin area or run the command php/bin magento cache:flush to finish all the steps.
Login in the frontend and then login in admin, go to Customers->All Customers -> Edit on the account you have logged in.
Click on the account information
