I would like to create a customer account programmatically in Magento 2.0.4.
I just have one problem. I don't know how to persist custom attributes. With following code, I got response that my required custom attribute (xxx_test) is not set.
class Register extends \Magento\Framework\App\Action\Action {
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);
$customer->setEmail("test@mail.com");
$customer->setFirstname("First Name");
$customer->setLastname("Last name");
$customer->setPassword("password");
$customer->setPrefix("Herr");
$customer->setAddresses(null);
$storeId = $this->storeManager->getWebsite($websiteId)->getDefaultStore()->getId();
$customer->setStoreId($storeId);
$storeName = $this->storeManager->getStore($customer->getStoreId())->getName();
$customer->setCreatedIn($storeName);
/*
* TODO
* Problem with custom attributes
*/
$customerData = $customer->getDataModel();
$customerData->setCustomAttribute("xxx_test", "N/A");
$customer->updateData($customerData);
$customer->save();
$customer->sendNewAccountEmail();
}
}
Could anybody please help?