How to add a customer programmatically in Magento 2?Magento 2 create customer programmatically not workingcustom form save and create customer in magentoCustom register formSave a new customerI Create a custom module in Magento 2.0 (Add/Edit Customer Attribute) but i am faceing a problem in prepare grid in magento 2.0 backendHow to add extension attributes to Customer entity in Magento2?Magento 2: Programmatically Updating InventoryHow add category programmatically magento 2Magento 2. How to add recently viewed products programmaticallyMagento 2.0 Add custom payment and shipping method on programmatically created orderMagento 2 Add Bundled Product to Cart ProgrammaticallyHow to add new breakpoint in magento 2?How Change Shopping Cart Page Title programmaticallymodule-customer phtml override

I am a dual citizen of United States and Mexico, can I use my Mexican license in california when visiting?

Calculating Fibonacci sequence in several different ways

Does switching on an old games console without a cartridge damage it?

How should I handle a question regarding my regrets during an interview?

Why are the phonemes of Tutankhamun's throne name transliterated out of order?

Why Lie algebras if what we care about in physics are groups?

Cargo capacity of a kayak

Has Iron Man made any suit for underwater combat?

Is it OK to accept a job opportunity while planning on not taking it?

Are Linux kernel modules a sort of Linux system paged pool?

How does mathematics work?

Considerations when providing money to only one child out of two

How to deal with making design decisions

Capture SQL Server queries without third-party tooling and without using deprecated features?

If hash functions append the length, why does length extension attack work?

Can a creature sustain itself by eating its own severed body parts?

I have a domain, static IP and many devices I'd like to access outside my house. How to route them?

How did pilots avoid thunderstorms and related weather before “reliable” airborne weather radar was introduced on airliners?

What kind of curve (or model) should I fit to my percentage data?

Why did modems have speakers?

How can I show that the speed of light in vacuum is the same in all reference frames?

Counterexample finite intersection property

Magic is the twist

Why is there an extra "t" in Lemmatization?



How to add a customer programmatically in Magento 2?


Magento 2 create customer programmatically not workingcustom form save and create customer in magentoCustom register formSave a new customerI Create a custom module in Magento 2.0 (Add/Edit Customer Attribute) but i am faceing a problem in prepare grid in magento 2.0 backendHow to add extension attributes to Customer entity in Magento2?Magento 2: Programmatically Updating InventoryHow add category programmatically magento 2Magento 2. How to add recently viewed products programmaticallyMagento 2.0 Add custom payment and shipping method on programmatically created orderMagento 2 Add Bundled Product to Cart ProgrammaticallyHow to add new breakpoint in magento 2?How Change Shopping Cart Page Title programmaticallymodule-customer phtml override






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








12















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();










share|improve this question
























  • you want to do this in a standalone script, or you have a model or something?

    – Marius
    Aug 10 '15 at 5:28











  • @Marius, I have been working on this module and I have created a controller. It this controller I need to prepare some data to be saved and the idea is to call the customer model and save that information. The code above can be placed in a controller I would like to do the same but for Magento 2. I am still a bit confused with the new structure of Magento 2 and stuck here now.. I know It has something to do with class injections and object instances but I am not sure how to do it...

    – Eduardo
    Aug 10 '15 at 15:06

















12















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();










share|improve this question
























  • you want to do this in a standalone script, or you have a model or something?

    – Marius
    Aug 10 '15 at 5:28











  • @Marius, I have been working on this module and I have created a controller. It this controller I need to prepare some data to be saved and the idea is to call the customer model and save that information. The code above can be placed in a controller I would like to do the same but for Magento 2. I am still a bit confused with the new structure of Magento 2 and stuck here now.. I know It has something to do with class injections and object instances but I am not sure how to do it...

    – Eduardo
    Aug 10 '15 at 15:06













12












12








12


5






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();










share|improve this 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();







magento-2.0






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Aug 25 '17 at 5:48









Teja Bhagavan Kollepara

3,0144 gold badges21 silver badges51 bronze badges




3,0144 gold badges21 silver badges51 bronze badges










asked Aug 10 '15 at 4:22









EduardoEduardo

4162 gold badges4 silver badges12 bronze badges




4162 gold badges4 silver badges12 bronze badges












  • you want to do this in a standalone script, or you have a model or something?

    – Marius
    Aug 10 '15 at 5:28











  • @Marius, I have been working on this module and I have created a controller. It this controller I need to prepare some data to be saved and the idea is to call the customer model and save that information. The code above can be placed in a controller I would like to do the same but for Magento 2. I am still a bit confused with the new structure of Magento 2 and stuck here now.. I know It has something to do with class injections and object instances but I am not sure how to do it...

    – Eduardo
    Aug 10 '15 at 15:06

















  • you want to do this in a standalone script, or you have a model or something?

    – Marius
    Aug 10 '15 at 5:28











  • @Marius, I have been working on this module and I have created a controller. It this controller I need to prepare some data to be saved and the idea is to call the customer model and save that information. The code above can be placed in a controller I would like to do the same but for Magento 2. I am still a bit confused with the new structure of Magento 2 and stuck here now.. I know It has something to do with class injections and object instances but I am not sure how to do it...

    – Eduardo
    Aug 10 '15 at 15:06
















you want to do this in a standalone script, or you have a model or something?

– Marius
Aug 10 '15 at 5:28





you want to do this in a standalone script, or you have a model or something?

– Marius
Aug 10 '15 at 5:28













@Marius, I have been working on this module and I have created a controller. It this controller I need to prepare some data to be saved and the idea is to call the customer model and save that information. The code above can be placed in a controller I would like to do the same but for Magento 2. I am still a bit confused with the new structure of Magento 2 and stuck here now.. I know It has something to do with class injections and object instances but I am not sure how to do it...

– Eduardo
Aug 10 '15 at 15:06





@Marius, I have been working on this module and I have created a controller. It this controller I need to prepare some data to be saved and the idea is to call the customer model and save that information. The code above can be placed in a controller I would like to do the same but for Magento 2. I am still a bit confused with the new structure of Magento 2 and stuck here now.. I know It has something to do with class injections and object instances but I am not sure how to do it...

– Eduardo
Aug 10 '15 at 15:06










4 Answers
4






active

oldest

votes


















20














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 ModuleNamespaceModule_NameControllerIndex;

class Index extends MagentoFrameworkAppActionAction

/**
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;

/**
* @var MagentoCustomerModelCustomerFactory
*/
protected $customerFactory;

/**
* @param MagentoFrameworkAppActionContext $context
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param MagentoCustomerModelCustomerFactory $customerFactory
*/
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoCustomerModelCustomerFactory $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..






share|improve this answer




















  • 6





    You were very close. You should avoid using objectManager directly whenever possible--it's bad form. The proper way to do that is using dependency injection to get the 'factory' class, and use that to create an instance. If a factory class doesn't exist for a given class, it'll be auto-generated. I've edited your code to use this (added the factory to the constructor and class, and calling create()), and follow the PSR-2 code standards.

    – Ryan Hoerr
    Aug 10 '15 at 23:02












  • Thanks for the correction @RyanH. I thought about using factory classes but wasn't sure how to, so I used objectManager... I will read more about PSR-2 code standards for future projects. I am using the code with your corrections now and everything work perfectly. Thanks

    – Eduardo
    Aug 12 '15 at 1:11












  • @RyanH. Done ; )

    – Eduardo
    Aug 12 '15 at 16:31











  • I can see it in databases but not for Admin panel. What happening?

    – Arni
    Dec 28 '15 at 20:46






  • 1





    @Arni; my first guess is that you'd need to reindex :)

    – Alex Timmer
    Sep 7 '16 at 8:08


















4














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



use MagentoFrameworkAppRequestFactory;
use MagentoCustomerModelCustomerExtractor;
use MagentoCustomerApiAccountManagementInterface;

class CreateCustomer extends MagentoFrameworkAppActionAction

/**
* @var RequestFactory
*/
protected $requestFactory;

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

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

/**
* @param MagentoFrameworkAppActionContext $context
* @param RequestFactory $requestFactory
* @param CustomerExtractor $customerExtractor
* @param AccountManagementInterface $customerAccountManagement
*/
public function __construct(
MagentoFrameworkAppActionContext $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








share|improve this answer























  • What is $request here?, can we add custom attributes also?

    – jafar pinjar
    Sep 5 '18 at 14:51












  • How to set custom attributes ?

    – jafar pinjar
    Sep 6 '18 at 7:27


















0














This code run in external file or console file CLI Magento



namespace CompanyModuleConsole;

use BraintreeException;
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleOutputOutputInterface;
use MagentoFrameworkAppBootstrap;


class ImportProducts extends Command


public function magentoStart()

$startMagento = $this->bootstrap();
$state = $startMagento['objectManager']->get('MagentoFrameworkAppState');
$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('MagentoStoreModelStoreManagerInterface');
$customerFactory = $objectManager->create('MagentoCustomerModelCustomerFactory');

$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();







share|improve this answer
































    0














    All above examples will work, but the standard way should always be the use of service contracts than the concrete classes.



    Hence, the below ways should be preferred for creating the customer programatically.



     /** @var MagentoCustomerApiDataCustomerInterface $customer */
    $customer = $this->customerFactory->create();
    $customer->setStoreId($store->getStoreId());
    $customer->setWebsiteId($store->getWebsiteId());
    $customer->setEmail($email);
    $customer->setFirstname($firstName);
    $customer->setLastname($lastName);

    /** @var MagentoCustomerApiCustomerRepositoryInterface $customerRepository*/
    $customerRepository->save($customer);





    share|improve this answer



























      Your Answer








      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "479"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f78164%2fhow-to-add-a-customer-programmatically-in-magento-2%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      20














      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 ModuleNamespaceModule_NameControllerIndex;

      class Index extends MagentoFrameworkAppActionAction

      /**
      * @var MagentoStoreModelStoreManagerInterface
      */
      protected $storeManager;

      /**
      * @var MagentoCustomerModelCustomerFactory
      */
      protected $customerFactory;

      /**
      * @param MagentoFrameworkAppActionContext $context
      * @param MagentoStoreModelStoreManagerInterface $storeManager
      * @param MagentoCustomerModelCustomerFactory $customerFactory
      */
      public function __construct(
      MagentoFrameworkAppActionContext $context,
      MagentoStoreModelStoreManagerInterface $storeManager,
      MagentoCustomerModelCustomerFactory $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..






      share|improve this answer




















      • 6





        You were very close. You should avoid using objectManager directly whenever possible--it's bad form. The proper way to do that is using dependency injection to get the 'factory' class, and use that to create an instance. If a factory class doesn't exist for a given class, it'll be auto-generated. I've edited your code to use this (added the factory to the constructor and class, and calling create()), and follow the PSR-2 code standards.

        – Ryan Hoerr
        Aug 10 '15 at 23:02












      • Thanks for the correction @RyanH. I thought about using factory classes but wasn't sure how to, so I used objectManager... I will read more about PSR-2 code standards for future projects. I am using the code with your corrections now and everything work perfectly. Thanks

        – Eduardo
        Aug 12 '15 at 1:11












      • @RyanH. Done ; )

        – Eduardo
        Aug 12 '15 at 16:31











      • I can see it in databases but not for Admin panel. What happening?

        – Arni
        Dec 28 '15 at 20:46






      • 1





        @Arni; my first guess is that you'd need to reindex :)

        – Alex Timmer
        Sep 7 '16 at 8:08















      20














      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 ModuleNamespaceModule_NameControllerIndex;

      class Index extends MagentoFrameworkAppActionAction

      /**
      * @var MagentoStoreModelStoreManagerInterface
      */
      protected $storeManager;

      /**
      * @var MagentoCustomerModelCustomerFactory
      */
      protected $customerFactory;

      /**
      * @param MagentoFrameworkAppActionContext $context
      * @param MagentoStoreModelStoreManagerInterface $storeManager
      * @param MagentoCustomerModelCustomerFactory $customerFactory
      */
      public function __construct(
      MagentoFrameworkAppActionContext $context,
      MagentoStoreModelStoreManagerInterface $storeManager,
      MagentoCustomerModelCustomerFactory $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..






      share|improve this answer




















      • 6





        You were very close. You should avoid using objectManager directly whenever possible--it's bad form. The proper way to do that is using dependency injection to get the 'factory' class, and use that to create an instance. If a factory class doesn't exist for a given class, it'll be auto-generated. I've edited your code to use this (added the factory to the constructor and class, and calling create()), and follow the PSR-2 code standards.

        – Ryan Hoerr
        Aug 10 '15 at 23:02












      • Thanks for the correction @RyanH. I thought about using factory classes but wasn't sure how to, so I used objectManager... I will read more about PSR-2 code standards for future projects. I am using the code with your corrections now and everything work perfectly. Thanks

        – Eduardo
        Aug 12 '15 at 1:11












      • @RyanH. Done ; )

        – Eduardo
        Aug 12 '15 at 16:31











      • I can see it in databases but not for Admin panel. What happening?

        – Arni
        Dec 28 '15 at 20:46






      • 1





        @Arni; my first guess is that you'd need to reindex :)

        – Alex Timmer
        Sep 7 '16 at 8:08













      20












      20








      20







      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 ModuleNamespaceModule_NameControllerIndex;

      class Index extends MagentoFrameworkAppActionAction

      /**
      * @var MagentoStoreModelStoreManagerInterface
      */
      protected $storeManager;

      /**
      * @var MagentoCustomerModelCustomerFactory
      */
      protected $customerFactory;

      /**
      * @param MagentoFrameworkAppActionContext $context
      * @param MagentoStoreModelStoreManagerInterface $storeManager
      * @param MagentoCustomerModelCustomerFactory $customerFactory
      */
      public function __construct(
      MagentoFrameworkAppActionContext $context,
      MagentoStoreModelStoreManagerInterface $storeManager,
      MagentoCustomerModelCustomerFactory $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..






      share|improve this answer















      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 ModuleNamespaceModule_NameControllerIndex;

      class Index extends MagentoFrameworkAppActionAction

      /**
      * @var MagentoStoreModelStoreManagerInterface
      */
      protected $storeManager;

      /**
      * @var MagentoCustomerModelCustomerFactory
      */
      protected $customerFactory;

      /**
      * @param MagentoFrameworkAppActionContext $context
      * @param MagentoStoreModelStoreManagerInterface $storeManager
      * @param MagentoCustomerModelCustomerFactory $customerFactory
      */
      public function __construct(
      MagentoFrameworkAppActionContext $context,
      MagentoStoreModelStoreManagerInterface $storeManager,
      MagentoCustomerModelCustomerFactory $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..







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Aug 11 '15 at 0:24









      Ryan Hoerr

      9,1095 gold badges35 silver badges48 bronze badges




      9,1095 gold badges35 silver badges48 bronze badges










      answered Aug 10 '15 at 22:11









      EduardoEduardo

      4162 gold badges4 silver badges12 bronze badges




      4162 gold badges4 silver badges12 bronze badges







      • 6





        You were very close. You should avoid using objectManager directly whenever possible--it's bad form. The proper way to do that is using dependency injection to get the 'factory' class, and use that to create an instance. If a factory class doesn't exist for a given class, it'll be auto-generated. I've edited your code to use this (added the factory to the constructor and class, and calling create()), and follow the PSR-2 code standards.

        – Ryan Hoerr
        Aug 10 '15 at 23:02












      • Thanks for the correction @RyanH. I thought about using factory classes but wasn't sure how to, so I used objectManager... I will read more about PSR-2 code standards for future projects. I am using the code with your corrections now and everything work perfectly. Thanks

        – Eduardo
        Aug 12 '15 at 1:11












      • @RyanH. Done ; )

        – Eduardo
        Aug 12 '15 at 16:31











      • I can see it in databases but not for Admin panel. What happening?

        – Arni
        Dec 28 '15 at 20:46






      • 1





        @Arni; my first guess is that you'd need to reindex :)

        – Alex Timmer
        Sep 7 '16 at 8:08












      • 6





        You were very close. You should avoid using objectManager directly whenever possible--it's bad form. The proper way to do that is using dependency injection to get the 'factory' class, and use that to create an instance. If a factory class doesn't exist for a given class, it'll be auto-generated. I've edited your code to use this (added the factory to the constructor and class, and calling create()), and follow the PSR-2 code standards.

        – Ryan Hoerr
        Aug 10 '15 at 23:02












      • Thanks for the correction @RyanH. I thought about using factory classes but wasn't sure how to, so I used objectManager... I will read more about PSR-2 code standards for future projects. I am using the code with your corrections now and everything work perfectly. Thanks

        – Eduardo
        Aug 12 '15 at 1:11












      • @RyanH. Done ; )

        – Eduardo
        Aug 12 '15 at 16:31











      • I can see it in databases but not for Admin panel. What happening?

        – Arni
        Dec 28 '15 at 20:46






      • 1





        @Arni; my first guess is that you'd need to reindex :)

        – Alex Timmer
        Sep 7 '16 at 8:08







      6




      6





      You were very close. You should avoid using objectManager directly whenever possible--it's bad form. The proper way to do that is using dependency injection to get the 'factory' class, and use that to create an instance. If a factory class doesn't exist for a given class, it'll be auto-generated. I've edited your code to use this (added the factory to the constructor and class, and calling create()), and follow the PSR-2 code standards.

      – Ryan Hoerr
      Aug 10 '15 at 23:02






      You were very close. You should avoid using objectManager directly whenever possible--it's bad form. The proper way to do that is using dependency injection to get the 'factory' class, and use that to create an instance. If a factory class doesn't exist for a given class, it'll be auto-generated. I've edited your code to use this (added the factory to the constructor and class, and calling create()), and follow the PSR-2 code standards.

      – Ryan Hoerr
      Aug 10 '15 at 23:02














      Thanks for the correction @RyanH. I thought about using factory classes but wasn't sure how to, so I used objectManager... I will read more about PSR-2 code standards for future projects. I am using the code with your corrections now and everything work perfectly. Thanks

      – Eduardo
      Aug 12 '15 at 1:11






      Thanks for the correction @RyanH. I thought about using factory classes but wasn't sure how to, so I used objectManager... I will read more about PSR-2 code standards for future projects. I am using the code with your corrections now and everything work perfectly. Thanks

      – Eduardo
      Aug 12 '15 at 1:11














      @RyanH. Done ; )

      – Eduardo
      Aug 12 '15 at 16:31





      @RyanH. Done ; )

      – Eduardo
      Aug 12 '15 at 16:31













      I can see it in databases but not for Admin panel. What happening?

      – Arni
      Dec 28 '15 at 20:46





      I can see it in databases but not for Admin panel. What happening?

      – Arni
      Dec 28 '15 at 20:46




      1




      1





      @Arni; my first guess is that you'd need to reindex :)

      – Alex Timmer
      Sep 7 '16 at 8:08





      @Arni; my first guess is that you'd need to reindex :)

      – Alex Timmer
      Sep 7 '16 at 8:08













      4














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



      use MagentoFrameworkAppRequestFactory;
      use MagentoCustomerModelCustomerExtractor;
      use MagentoCustomerApiAccountManagementInterface;

      class CreateCustomer extends MagentoFrameworkAppActionAction

      /**
      * @var RequestFactory
      */
      protected $requestFactory;

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

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

      /**
      * @param MagentoFrameworkAppActionContext $context
      * @param RequestFactory $requestFactory
      * @param CustomerExtractor $customerExtractor
      * @param AccountManagementInterface $customerAccountManagement
      */
      public function __construct(
      MagentoFrameworkAppActionContext $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








      share|improve this answer























      • What is $request here?, can we add custom attributes also?

        – jafar pinjar
        Sep 5 '18 at 14:51












      • How to set custom attributes ?

        – jafar pinjar
        Sep 6 '18 at 7:27















      4














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



      use MagentoFrameworkAppRequestFactory;
      use MagentoCustomerModelCustomerExtractor;
      use MagentoCustomerApiAccountManagementInterface;

      class CreateCustomer extends MagentoFrameworkAppActionAction

      /**
      * @var RequestFactory
      */
      protected $requestFactory;

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

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

      /**
      * @param MagentoFrameworkAppActionContext $context
      * @param RequestFactory $requestFactory
      * @param CustomerExtractor $customerExtractor
      * @param AccountManagementInterface $customerAccountManagement
      */
      public function __construct(
      MagentoFrameworkAppActionContext $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








      share|improve this answer























      • What is $request here?, can we add custom attributes also?

        – jafar pinjar
        Sep 5 '18 at 14:51












      • How to set custom attributes ?

        – jafar pinjar
        Sep 6 '18 at 7:27













      4












      4








      4







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



      use MagentoFrameworkAppRequestFactory;
      use MagentoCustomerModelCustomerExtractor;
      use MagentoCustomerApiAccountManagementInterface;

      class CreateCustomer extends MagentoFrameworkAppActionAction

      /**
      * @var RequestFactory
      */
      protected $requestFactory;

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

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

      /**
      * @param MagentoFrameworkAppActionContext $context
      * @param RequestFactory $requestFactory
      * @param CustomerExtractor $customerExtractor
      * @param AccountManagementInterface $customerAccountManagement
      */
      public function __construct(
      MagentoFrameworkAppActionContext $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








      share|improve this answer













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



      use MagentoFrameworkAppRequestFactory;
      use MagentoCustomerModelCustomerExtractor;
      use MagentoCustomerApiAccountManagementInterface;

      class CreateCustomer extends MagentoFrameworkAppActionAction

      /**
      * @var RequestFactory
      */
      protected $requestFactory;

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

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

      /**
      * @param MagentoFrameworkAppActionContext $context
      * @param RequestFactory $requestFactory
      * @param CustomerExtractor $customerExtractor
      * @param AccountManagementInterface $customerAccountManagement
      */
      public function __construct(
      MagentoFrameworkAppActionContext $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









      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Aug 25 '17 at 7:08









      Nicholas MillerNicholas Miller

      9234 silver badges13 bronze badges




      9234 silver badges13 bronze badges












      • What is $request here?, can we add custom attributes also?

        – jafar pinjar
        Sep 5 '18 at 14:51












      • How to set custom attributes ?

        – jafar pinjar
        Sep 6 '18 at 7:27

















      • What is $request here?, can we add custom attributes also?

        – jafar pinjar
        Sep 5 '18 at 14:51












      • How to set custom attributes ?

        – jafar pinjar
        Sep 6 '18 at 7:27
















      What is $request here?, can we add custom attributes also?

      – jafar pinjar
      Sep 5 '18 at 14:51






      What is $request here?, can we add custom attributes also?

      – jafar pinjar
      Sep 5 '18 at 14:51














      How to set custom attributes ?

      – jafar pinjar
      Sep 6 '18 at 7:27





      How to set custom attributes ?

      – jafar pinjar
      Sep 6 '18 at 7:27











      0














      This code run in external file or console file CLI Magento



      namespace CompanyModuleConsole;

      use BraintreeException;
      use SymfonyComponentConsoleCommandCommand;
      use SymfonyComponentConsoleInputInputInterface;
      use SymfonyComponentConsoleOutputOutputInterface;
      use MagentoFrameworkAppBootstrap;


      class ImportProducts extends Command


      public function magentoStart()

      $startMagento = $this->bootstrap();
      $state = $startMagento['objectManager']->get('MagentoFrameworkAppState');
      $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('MagentoStoreModelStoreManagerInterface');
      $customerFactory = $objectManager->create('MagentoCustomerModelCustomerFactory');

      $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();







      share|improve this answer





























        0














        This code run in external file or console file CLI Magento



        namespace CompanyModuleConsole;

        use BraintreeException;
        use SymfonyComponentConsoleCommandCommand;
        use SymfonyComponentConsoleInputInputInterface;
        use SymfonyComponentConsoleOutputOutputInterface;
        use MagentoFrameworkAppBootstrap;


        class ImportProducts extends Command


        public function magentoStart()

        $startMagento = $this->bootstrap();
        $state = $startMagento['objectManager']->get('MagentoFrameworkAppState');
        $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('MagentoStoreModelStoreManagerInterface');
        $customerFactory = $objectManager->create('MagentoCustomerModelCustomerFactory');

        $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();







        share|improve this answer



























          0












          0








          0







          This code run in external file or console file CLI Magento



          namespace CompanyModuleConsole;

          use BraintreeException;
          use SymfonyComponentConsoleCommandCommand;
          use SymfonyComponentConsoleInputInputInterface;
          use SymfonyComponentConsoleOutputOutputInterface;
          use MagentoFrameworkAppBootstrap;


          class ImportProducts extends Command


          public function magentoStart()

          $startMagento = $this->bootstrap();
          $state = $startMagento['objectManager']->get('MagentoFrameworkAppState');
          $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('MagentoStoreModelStoreManagerInterface');
          $customerFactory = $objectManager->create('MagentoCustomerModelCustomerFactory');

          $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();







          share|improve this answer















          This code run in external file or console file CLI Magento



          namespace CompanyModuleConsole;

          use BraintreeException;
          use SymfonyComponentConsoleCommandCommand;
          use SymfonyComponentConsoleInputInputInterface;
          use SymfonyComponentConsoleOutputOutputInterface;
          use MagentoFrameworkAppBootstrap;


          class ImportProducts extends Command


          public function magentoStart()

          $startMagento = $this->bootstrap();
          $state = $startMagento['objectManager']->get('MagentoFrameworkAppState');
          $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('MagentoStoreModelStoreManagerInterface');
          $customerFactory = $objectManager->create('MagentoCustomerModelCustomerFactory');

          $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();








          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 30 at 19:18









          Rama Chandran M

          2,7978 gold badges16 silver badges30 bronze badges




          2,7978 gold badges16 silver badges30 bronze badges










          answered Jan 30 at 18:57









          Israel GuidoIsrael Guido

          331 silver badge8 bronze badges




          331 silver badge8 bronze badges





















              0














              All above examples will work, but the standard way should always be the use of service contracts than the concrete classes.



              Hence, the below ways should be preferred for creating the customer programatically.



               /** @var MagentoCustomerApiDataCustomerInterface $customer */
              $customer = $this->customerFactory->create();
              $customer->setStoreId($store->getStoreId());
              $customer->setWebsiteId($store->getWebsiteId());
              $customer->setEmail($email);
              $customer->setFirstname($firstName);
              $customer->setLastname($lastName);

              /** @var MagentoCustomerApiCustomerRepositoryInterface $customerRepository*/
              $customerRepository->save($customer);





              share|improve this answer





























                0














                All above examples will work, but the standard way should always be the use of service contracts than the concrete classes.



                Hence, the below ways should be preferred for creating the customer programatically.



                 /** @var MagentoCustomerApiDataCustomerInterface $customer */
                $customer = $this->customerFactory->create();
                $customer->setStoreId($store->getStoreId());
                $customer->setWebsiteId($store->getWebsiteId());
                $customer->setEmail($email);
                $customer->setFirstname($firstName);
                $customer->setLastname($lastName);

                /** @var MagentoCustomerApiCustomerRepositoryInterface $customerRepository*/
                $customerRepository->save($customer);





                share|improve this answer



























                  0












                  0








                  0







                  All above examples will work, but the standard way should always be the use of service contracts than the concrete classes.



                  Hence, the below ways should be preferred for creating the customer programatically.



                   /** @var MagentoCustomerApiDataCustomerInterface $customer */
                  $customer = $this->customerFactory->create();
                  $customer->setStoreId($store->getStoreId());
                  $customer->setWebsiteId($store->getWebsiteId());
                  $customer->setEmail($email);
                  $customer->setFirstname($firstName);
                  $customer->setLastname($lastName);

                  /** @var MagentoCustomerApiCustomerRepositoryInterface $customerRepository*/
                  $customerRepository->save($customer);





                  share|improve this answer















                  All above examples will work, but the standard way should always be the use of service contracts than the concrete classes.



                  Hence, the below ways should be preferred for creating the customer programatically.



                   /** @var MagentoCustomerApiDataCustomerInterface $customer */
                  $customer = $this->customerFactory->create();
                  $customer->setStoreId($store->getStoreId());
                  $customer->setWebsiteId($store->getWebsiteId());
                  $customer->setEmail($email);
                  $customer->setFirstname($firstName);
                  $customer->setLastname($lastName);

                  /** @var MagentoCustomerApiCustomerRepositoryInterface $customerRepository*/
                  $customerRepository->save($customer);






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jul 13 at 10:46

























                  answered Jul 13 at 10:40









                  Milind SinghMilind Singh

                  8462 silver badges15 bronze badges




                  8462 silver badges15 bronze badges



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Magento Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f78164%2fhow-to-add-a-customer-programmatically-in-magento-2%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

                      Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

                      Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form