Thursday 27 February 2020

save new customer magento2

class Index extends \Magento\Framework\App\Action\Action
{
    protected $storeManager;
    protected $customerFactory;
    protected $messageManager;
 
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
\Magento\Framework\Message\ManagerInterface $messageManager
    ){
        $this->storeManager     = $storeManager;
        $this->customerFactory  = $customerFactory;
$this->messageManager = $messageManager;
        parent::__construct($context);
    }

    public function execute()
    {
$post = $this->getRequest()->getPostValue();/*******post request*************/
if(isset($post['name'])){
$websiteId  = $this->storeManager->getWebsite()->getWebsiteId();
try {
      $customer   = $this->customerFactory->create();
      $customer->setWebsiteId($websiteId);
      $customer->setEmail($post['email']);
      $customer->setFirstname($post['name']);
      $customer->setLastname($post['name']);
      $customer->setTelephone($post['phone']);
      $password = rand();
      $newhash = hash('sha256', $password);
                  $customer->setPassword($newhash);
          $customer->save();
      $this->messageManager->addSuccess(__("Customer added successfully"));
      $customer->sendNewAccountEmail();
}
}catch (Exception $e) {
echo $e->getMessage();
}

}
        $this->_view->loadLayout();
        $this->_view->getLayout()->initMessages();
        $this->_view->renderLayout();
    }
}