Magento 2 Customer – How to Set Customer Custom Attribute

custom-attributescustomercustomer-attributemagento2

I have created some custom attributes for a customer in magento2 community edition,

I have used below code to set in my custom code

use Magento\Customer\Api\AccountManagementInterface;
use Magento\Framework\App\Action\Context;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Model\CustomerExtractor;

class CreateCustomer extends \Magento\Customer\Controller\AbstractAccount
 {
  protected $customerRepository;
  protected $accountManagement;
  protected $customerExtractor;

  public function __construct(
    Context $context,
    AccountManagementInterface $accountManagement,
    CustomerExtractor $customerExtractor,
  ) {
    $this->accountManagement = $accountManagement;
    $this->customerExtractor = $customerExtractor;
   parent::__construct($context);
}
  public function execute()
{
  try {
       $customer = $this->customerExtractor->extract('customer_account_create', $this->_request);
        $password = $this->getRequest()->getParam('password');
        $confirmation = $this->getRequest()->getParam('password_confirmation');

        $customer = $this->accountManagement
            ->createAccount($customer, $password, $redirectUrl);

         $this->customerRepository = ObjectManager::getInstance()->get(
            \Magento\Customer\Api\CustomerRepositoryInterface::class
        );  

        $customer->setCustomAttribute('is_checked', 0);
        $this->customerRepository->save($customer);    
 }catch (StateException $e) {
      print_r($e->getMessage());
   }
  }
}
 $customer->setCustomAttribute('is_checked', 0);

This attribute is a custom attribute and I have set default_value as 0, but it is not saving on creating a customer. I can't see any value in the table for any of the customers.

This is not storing in the table. What is the reason please anyone helps me with this.

Here is the screenshot for the attribute in the table

enter image description here

attribute_code is customer_activated.

Best Answer

Try that code to save custom attribute of customer

$customerRepository = $this->objectManager->get('Magento\Customer\Api\CustomerRepositoryInterface');

$customer = $customerRepository->getById('customer_id');

$customer->setCustomAttribute("is_checked",'0');

$customerRepository->save($customer);
Related Topic