protected $storeManager;
protected $customerFactory;
public function __construct(
\Magento\Catalog\Block\Product\Context $context,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Customer\Model\CustomerFactory $customerFactory,
array $data = []
) {
$this->storeManager = $storeManager;
$this->customerFactory = $customerFactory;
parent::__construct($context, $data);
}
public function addCustomer($firstName, $lastName, $email, $password)
{
$store = $this->storeManager->getStore();
$websiteId = $this->storeManager->getWebsite()->getWebsiteId();
$customer = $this->customerFactory->create();
// Set website ID
$customer->setWebsiteId($websiteId);
// Set Store
$customer->setStore($store);
// Check if customer is already exists
if ($customer->loadByEmail($email)->getId()) {
return __('There is already an account with this email address "%1".', $email);
} else {
$customer->setEmail($email);
$customer->setFirstname($firstName);
$customer->setLastname($lastName);
$customer->setPassword($password);
$customer->setForceConfirmed(true);
// Save customer data
$customer->save();
// Send email
$customer->sendNewAccountEmail();
return __('Customer account with email %1 created successfully.', $email);
}
}
Recent Comments