In Magento 2, some times we need to create customer programmatically.
You can use the below code to convert guest orders to customer or Convert guest to a customer too.
How to create customer using controller.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
<?php /** * @category Customer Create * @package CWM * @author Coffee with magento */ namespace CWM\CustomerCreate\Controller\Index; class Index extends \Magento\Framework\App\Action\Action { /** * @var \Magento\Store\Model\StoreManagerInterface */ protected $storeManager; /** * @var \Magento\Customer\Model\CustomerFactory */ protected $customerModelFactory; /** * @param \Magento\Framework\App\Action\Context $context * @param \Magento\Store\Model\StoreManagerInterface $storeManager * @param \Magento\Customer\Model\CustomerFactory $customerModelFactory */ public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Customer\Model\CustomerFactory $customerModelFactory ) { $this->storeManager = $storeManager; $this->customerModelFactory = $customerModelFactory; parent::__construct($context); } public function execute() { // we need website for customer, so we can set on which website this customer need to create $websiteId = $this->storeManager->getWebsite()->getWebsiteId(); $customer = $this->customerFactory->create(); $customer->setWebsiteId($websiteId); $customer->setEmail("coffeewithmagento@coffee.com"); $customer->setFirstname("Coffee"); $customer->setLastname("Magento"); $customer->setPassword("iampassword"); try { $customer->save(); // If wanted to send new account email to customer $customer->sendNewAccountEmail(); } catch (\Exception $e) { // var_dump($e->getMessage()); } } } |
Using above code, our question How to create customer is solved.