Creating customers programmatically in Magento 2 is so simple. Just pass the required parameter to the customer array as below and create a PHP block or helper file and call createCustomer() function,
In the template file,
<?php
$customerInfo =[
'customer' =>[
'firstname' => 'Rakesh1',
'email' => 'rakesh.jesadiya@aaaaaaaa.com', //customer email id
'lastname' => 'Jesadiya',
'password' => 'admin123',
'prefix' => 'Mr',
'suffix' => ''
]
];
$block->createCustomer($customerInfo);
?>
In the Block file, Pass customer-required data from the above $customerInfo array,
<?php
namespace Rbj\CreateCustomer\Block;
class Customer extends \Magento\Framework\View\Element\Template
{
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Customer\Model\CustomerFactory $customerFactory,
array $data = []
) {
$this->storeManager = $storeManager;
$this->customerFactory = $customerFactory;
parent::__construct($context, $data);
}
/** Create customer
* Pass customer data as array
*/
public function createCustomer($data) {
$store = $this->storeManager->getStore();
$storeId = $store->getStoreId();
$websiteId = $this->storeManager->getStore()->getWebsiteId();
$customer = $this->customerFactory->create();
$customer->setWebsiteId($websiteId);
$customer->loadByEmail($data['customer']['email']);// load customer by email address
if(!$customer->getId()){
//For guest customer create new cusotmer
$customer->setWebsiteId($websiteId)
->setStore($store)
->setFirstname($data['customer']['firstname'])
->setLastname($data['customer']['lastname'])
->setPrefix($data['customer']['prefix'])
->setEmail($data['customer']['email'])
->setPassword($data['customer']['password']);
$customer->save();
}
}
}
Run Command,
php bin/magento indexer:reindex php bin/magento cache:flush
Go to Admin panel, Login your admin panel with username and password, Click on Customers Tab -> All Customer
Your new customer will be generated successfully.
