I want to get id of the customer when I add new record of customer new account in customer_save_before
event.
Id will be display before record saved in customer_entity table.
How to get id using customer_save_before
in observer?
Please help me.
I want to get id of the customer when I add new record of customer new account in customer_save_before
event.
Id will be display before record saved in customer_entity table.
How to get id using customer_save_before
in observer?
Please help me.
As per as your comment, you want validate customer mobile no before have whenever new customer is created or record is updated.
In this you can use your customer_save_before
event:
and observer may be like this:
<?php
namespace Devamitbera\MobileCheck\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Exception\AlreadyExistsException;
class ValidateMobileNo implements ObserverInterface
{
protected $_customerCollectionFactory;
public function __construct(
\Magento\Customer\Model\ResourceModel\Customer\CollectionFactory $customerCollectionFactory,
) {
$this->_customerCollectionFactory = $customerCollectionFactory;
}
/**
*
* @param \Magento\Framework\Event\Observer $observer
* @return void
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
$customer = $observer->getCustomer();
$customerCollection= $this->_customerCollectionFactory->create();
$customerCollection->addAttribuTeToFilter('[YOUR_ATTRUBUTE]',$customer->getData('[YOUR_ATTRUBUTE]'));
if ($customer->getId()) {
$customerCollection->addAttribuTeToFilter('entity_id',array('neq' => (int)$customer->getId()));
}
if($customerCollection->getSize()>0){
throw new AlreadyExistsException(
__('A customer with the same Mobile already exists .')
);
}
}
}
I have not tried it myself but dig into Magento core files and got this solution.
Please look into this class:
Magento\Framework\Model\ResourceModel\Db\AbstractDb
Into the function named saveNewObject() around line number 762
$object->setId($this->getConnection()->lastInsertId($this->getMainTable()));
using the lastInsertId() one can get the last added Id in particular table by passing the name of the table.
Hope, this will help you.