7

How can I save a custom Customer Attribute value programmatically? I have tried below code but it didn't work.

protected $customer;

public function __construct(
    \Magento\Customer\Model\Customer $customer
)
{
    $this->customer = $customer;
}

...
...

$customerId = "1";
$customer = $this->customer->load($customerId);
$data = "customer attribute value";
$customerData = $customer->getDataModel();
$customerData->setCustomAttribute('customer_attribute_code',$data);
$customer->updateData($customerData);
$customer->save();

Is there any other method to save the customer attribute?

6 Answers 6

16

I have got the solution

protected $customer;

protected $customerFactory;

public function __construct(
    \Magento\Customer\Model\Customer $customer,
    \Magento\Customer\Model\ResourceModel\CustomerFactory $customerFactory
)
{
    $this->customer = $customer;
    $this->customerFactory = $customerFactory;
}

...
...

$customerId = "1";
$customer = $this->customer->load($customerId);
$data = "customer attribute value";
$customerData = $customer->getDataModel();
$customerData->setCustomAttribute('customer_attribute_code',$data);
$customer->updateData($customerData);
$customerResource = $this->customerFactory->create();
$customerResource->saveAttribute($customer, 'customer_attribute_code');
6
  • 3
    This code not working in magento 2.2.3, please suggest if you have any alternate solution please share as I want to save custom customer address attribute value programmatically. Commented Mar 28, 2018 at 13:26
  • 1
    @Dinesh , Best Solution ever I got. Working for all types of customer attributes.
    – TBS Mage
    Commented Jun 19, 2018 at 7:07
  • 2
    @TBSMage, Thank you for your valuable comment :) Commented Jun 19, 2018 at 7:33
  • I have created attribute of type int, that is not saving if i use below code $customerData->setCustomAttribute('customer_check', 1); Commented Aug 28, 2018 at 8:50
  • @DineshYadav, how to save customer custom address values? Commented Feb 1, 2019 at 12:14
7

You need to do it the strange Magento 2 way:-

public function __construct(
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
) {
    $this->_customerRepository = $customerRepository;
}

public function execute()
{
    $customer = $this->_customerRepository->getById($customerId);
    $customer->setDob($data['dob'])
             ->setCustomAttribute('medicare_number',$data['medicare_number'])
             ->setCustomAttribute('medicare_reference',$data['medicare_reference'])
             ->setCustomAttribute('medicare_exp',$data['medicare_exp']);
    $this->_customerRepository->save($customer);
}
2
  • 1
    Using this approach, you will get exceptions when you save the customer when the customer's address is not complete. For example, no street address, region, etc.
    – phagento
    Commented Aug 22, 2021 at 9:07
  • how about if you have a custom multiselect attribute ? Commented Jan 26, 2022 at 13:10
1

Some times, you may need to save multiple attributes at the same time. After go through the Magento code, I endup with this code. Here medicare_number and medicare_reference are custom attributes.

        $customerModel = $this->_customerFactory->create();
        $customerModel->getResource()->load($customerModel, $customerId);
        $customerModel->setData('dob', $this->getRequest()->getParam('dob'))
                    ->setData('gender', $this->getRequest()->getParam('gender'))
                    ->setData('medicare_number', $this->getRequest()->getParam('medicare_number'))
                    ->setData('medicare_reference', $this->getRequest()->getParam('medicare_reference'))
                    ->setAttributeSetId(\Magento\Customer\Api\CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER);
        $customerModel->getResource()->save($customerModel);
2
  • this is working in 2.2.5, tried dozens of other answers but none of them work, thank you! Commented Aug 30, 2018 at 19:42
  • short version for working code is something like $customer->setData('my_attribute', 1234) ->setAttributeSetId(\Magento\Customer\Api\CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER)->getResource()->save($customer) Commented Aug 30, 2018 at 19:43
0
protected $customer;

protected $customerFactory;

public function __construct(
    \Magento\Customer\Model\Customer $customer
    \Magento\Customer\Model\ResourceModel\CustomerFactory $customerFactory
)
{
    $this->customer = $customer;
    $this->customerFactory = $customerFactory;
}

...
...
    $mobile="1234567890";
    $custom = $this->_customerFactory ->create();
    $custom = $custom->setWebsiteId($helperData->getWebsiteId());
    $custom = $custom->loadByEmail("[email protected]");

    $customerData = $custom->getDataModel();
    $customerData->setCustomAttribute('custom_attribute code', $mobile);
    $custom->updateData($customerData);

    $custom->save();
0

Use this helper for Magento >2.4.2

<?php

namespace Company\Customer\Helper;

use Magento\Customer\Model\CustomerFactory;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    protected $customerFactory;

    public function __construct(
        CustomerFactory $customerFactory
    ) {
        $this->customerFactory = $customerFactory;
    }

    public function overrideCustomAttribute($pCustomer, $attributeCode, $value)
    {
        $customer = $this->customerFactory->create()->load($pCustomer->getId());

        $customerDataModel = $customer->getDataModel();
        $customerDataModel->setCustomAttribute($attributeCode, $value);
        $customer->updateData($customerDataModel);
        $customer->save();
    }

}
0

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;

}
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.