Question

I need to create a customer programmatically in Magento 2, I haven't found much documentation around... basically what I need to do is translate the following code into "Magento 2":

$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();

$customer = Mage::getModel("customer/customer");
$customer   ->setWebsiteId($websiteId)
            ->setStore($store)
            ->setFirstname('John')
            ->setLastname('Doe')
            ->setEmail('jd1@ex.com')
            ->setPassword('somepassword');

try{
    $customer->save();
}
Was it helpful?

Solution

Okay, after a while I found a solution in case someone else needs it.. Magento uses another approach to instantiate objects, the traditional way to instantiate objects in Magento 1.x was using "Mage::getModel(..)", this have changed in Magento 2. Now Magento uses an object manager to instantiate objets, I won't enter in details about how it works.. so, the equivalent code for creating customers in Magento 2 would look like this:

<?php

namespace ModuleNamespace\Module_Name\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @var \Magento\Customer\Model\CustomerFactory
     */
    protected $customerFactory;

    /**
     * @param \Magento\Framework\App\Action\Context      $context
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Customer\Model\CustomerFactory    $customerFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Customer\Model\CustomerFactory $customerFactory
    ) {
        $this->storeManager     = $storeManager;
        $this->customerFactory  = $customerFactory;

        parent::__construct($context);
    }

    public function execute()
    {
        // Get Website ID
        $websiteId  = $this->storeManager->getWebsite()->getWebsiteId();

        // Instantiate object (this is the most important part)
        $customer   = $this->customerFactory->create();
        $customer->setWebsiteId($websiteId);

        // Preparing data for new customer
        $customer->setEmail("email@domain.com"); 
        $customer->setFirstname("First Name");
        $customer->setLastname("Last name");
        $customer->setPassword("password");

        // Save data
        $customer->save();
        $customer->sendNewAccountEmail();
    }
}

Hope this snippet of code help someone else..

OTHER TIPS

Here is simple way to create a new customer with default group and current store.

use Magento\Framework\App\RequestFactory;
use Magento\Customer\Model\CustomerExtractor;
use Magento\Customer\Api\AccountManagementInterface;

class CreateCustomer extends \Magento\Framework\App\Action\Action
{
    /**
     * @var RequestFactory
     */
    protected $requestFactory;

    /**
     * @var CustomerExtractor
     */
    protected $customerExtractor;

    /**
     * @var AccountManagementInterface
     */
    protected $customerAccountManagement;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param RequestFactory $requestFactory
     * @param CustomerExtractor $customerExtractor
     * @param AccountManagementInterface $customerAccountManagement
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        RequestFactory $requestFactory,
        CustomerExtractor $customerExtractor,
        AccountManagementInterface $customerAccountManagement
    ) {
        $this->requestFactory = $requestFactory;
        $this->customerExtractor = $customerExtractor;
        $this->customerAccountManagement = $customerAccountManagement;
        parent::__construct($context);
    }

    /**
     * Retrieve sources
     *
     * @return array
     */
    public function execute()
    {
        $customerData = [
            'firstname' => 'First Name',
            'lastname' => 'Last Name',
            'email' => 'customer@email.com',
        ];

        $password = 'MyPass123'; //set null to auto-generate

        $request = $this->requestFactory->create();
        $request->setParams($customerData);

        try {
            $customer = $this->customerExtractor->extract('customer_account_create', $request);
            $customer = $this->customerAccountManagement->createAccount($customer, $password);
        } catch (\Exception $e) {
            //exception logic
        }
    }
}

All the above examples will work, but according to the coding standards you should always use service contracts than the concrete classes.

Hence, the following way should be preferred for creating customer account programmatically.


use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterfaceFactory;
use Magento\Store\Model\StoreManagerInterface;

class CustomerCreate
{
    public $store;

    public $customerFactory;

    public $customerRepository;

    public function __construct(
        StoreManagerInterface $store,
        CustomerInterfaceFactory $customerFactory,
        CustomerRepositoryInterface $customerRepository
    ) {
        $this->store = $store;
        $this->customerFactory = $customerFactory;
        $this->customerRepository = $customerRepository;
    }


    public function create()
    {
        try {
           /** @var \Magento\Customer\Api\Data\CustomerInterface $customer */
           $customer = $this->customerFactory->create();
           $customer->setStoreId($this->store->getStoreId());
           $customer->setWebsiteId($this->store->getWebsiteId());
           $customer->setEmail($email);
           $customer->setFirstname($firstName);
           $customer->setLastname($lastName);

           /** @var \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository*/
           $customer = $this->customerRepository->save($customer);
           // Note: The save returns the saved customer object, else throws an exception.
       } catch (\Exception $e) {
          // Add log
       }
    }

}

This code run in external file or console file CLI Magento

namespace Company\Module\Console;

use Braintree\Exception;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Magento\Framework\App\Bootstrap;


class ImportProducts extends Command
{

    public function magentoStart()
    {
        $startMagento = $this->bootstrap();
        $state = $startMagento['objectManager']->get('Magento\Framework\App\State');
        $state->setAreaCode('frontend');
        return $startMagento['objectManager'];
    }

    protected function bootstrap()
    {
        require '/var/www/html/app/bootstrap.php';
        $bootstrap = Bootstrap::create(BP, $_SERVER);
        $objectManager = $bootstrap->getObjectManager();
        return array('bootstrap' => $bootstrap, 'objectManager' => $objectManager);
    }

    protected function createCustomers($item)
    {
        $objectManager      = $this->magentoStart();
        $storeManager       = $objectManager->create('Magento\Store\Model\StoreManagerInterface');
        $customerFactory    = $objectManager->create('Magento\Customer\Model\CustomerFactory');

        $websiteId  = $storeManager->getWebsite()->getWebsiteId();
        $customer   = $customerFactory->create();
        $customer->setWebsiteId($websiteId);
        $customer->setEmail("eu@mailinator.com");
        $customer->setFirstname("First Name");
        $customer->setLastname("Last name");
        $customer->setPassword("password");
        $customer->save();
    }
}

The correct way to do this using modern Magento 2 interfaces is as follows. This will avoid deprecated function warnings:

    /**  @var CustomerInterfaceFactory $customerFactory */
    $customerFactory = $this->_bootstrap->getObjectManager()->get("\Magento\Customer\Api\Data\CustomerInterfaceFactory");

    $customer = $customerFactory->create();
    $customer->setWebsiteId(\ElectricLabs\MagentoHelpers::getCurrentStoreId());

    $customer->setEmail($emailAddress);
    $customer->setFirstname($firstName);
    $customer->setLastname($lastName);

    /**  @var CustomerRepositoryInterface $customerRepository */
    $customerRepository = $this->_bootstrap->getObjectManager()->get("\Magento\Customer\Api\CustomerRepositoryInterface");

    /**  @var Encryptor $encryptor */
    $encryptor = $this->_bootstrap->getObjectManager()->get("\Magento\Framework\Encryption\Encryptor");
    $passwordHash = $encryptor->getHash($password, true);
    $customer = $customerRepository->save($customer, $passwordHash);


    /**  @var SessionFactory $customerSessionFactory */
    $customerSessionFactory = $this->_bootstrap->getObjectManager()->get('Magento\Customer\Model\SessionFactory');
    $session = $customerSessionFactory->create();
    $session->setCustomerDataAsLoggedIn($customer);

    /**  @var EmailNotification $emailNotification */
    $emailNotification = $this->_bootstrap->getObjectManager()->get("\Magento\Customer\Model\EmailNotification");
    $emailNotification->newAccount($customer);
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top