Refer below code: website Id is required
<?php
namespace Devji\Customer\Model;
use Magento\Customer\Model\CustomerFactory;
use Magento\Customer\Model\Customer;
use Magento\Store\Model\StoreManagerInterface;
class UpdateCardNumber
{
/**
* @var StoreManagerInterface
*/
protected $_storeManager;
/**
* @var CustomerFactory
*/
protected $_customerFactory;
/**
* @var Customer
*/
protected $_customer;
/**
* UpdateCardNumber constructor.
* @param CustomerFactory $customerFactory
* @param Customer $customers
* @param StoreManagerInterface $storeManager
*/
public function __construct(
CustomerFactory $customerFactory,
Customer $customers,
StoreManagerInterface $storeManager
)
{
$this->_storeManager = $storeManager;
$this->_customerFactory = $customerFactory;
$this->_customer = $customers;
}
/**
* Update customer attribute
*/
public function updateCustomerCardNumber()
{
try {
$customerCollection = $this->_customer->getCollection()
->addAttributeToSelect("*")
->addAttributeToFilter(
array(
array('attribute' => 'reward_card_number', 'null' => true),
array('attribute' => 'reward_card_number', 'eq' => ''),
array('attribute' => 'reward_card_number', 'eq' => 'NO FIELD')
),
'',
'left')
->load();
$websiteId = $this->_storeManager->getDefaultStoreView()->getWebsiteId();
foreach ($customerCollection as $customer) {
if (!empty($customer->getEntityId())) {
$customer = $this->_customerFactory->create()->load($customer->getEntityId());
$customerDataModel = $customer->getDataModel();
$customerDataModel->setWebsiteId($websiteId);
$customerDataModel->setCustomAttribute('reward_card_number',
$this->getCardNumber($customer->getEntityId()));
$customer->updateData($customerDataModel);
$customer->save();
}
}
} catch (\Exception $e) {
echo $e->getMessage();
}
echo "Done";
return;
}
/**
* Get Card number
* @param $customerId
* @return string
*/
public function getCardNumber($customerId){
$year = date('y');
$month = date('m');
$customerId = sprintf("%010s", $customerId);
return '99'.$year.$month.$customerId;
}
}