7

I have created custom attribute for customer using below code.

setup/installData.php

class InstallData implements InstallDataInterface {

const LEGALITY_DOCUMENT_1 = 'user_legality_document_1';
protected $customerSetupFactory;
private $attributeSetFactory;


public function __construct(
CustomerSetupFactory $customerSetupFactory, AttributeSetFactory $attributeSetFactory
) {

    $this->customerSetupFactory = $customerSetupFactory;
    $this->attributeSetFactory = $attributeSetFactory;
}

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {
    $setup->startSetup();
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

        $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
        $attributeSetId = $customerEntity->getDefaultAttributeSetId();

        $attributeSet = $this->attributeSetFactory->create();
        $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

    $customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, self::LEGALITY_DOCUMENT_1, [
        'type' => 'varchar',
        'label' => 'Legal Document',
        'input' => 'image',
        "source" => '',
        'required' => false,
        'default' => '0',
        'visible' => true,
        'user_defined' => true,
        'sort_order' => 210,
        'position' => 210,
        'system' => false,
    ]);

    $document = $customerSetup->getEavConfig()->getAttribute(\Magento\Customer\Model\Customer::ENTITY, self::LEGALITY_DOCUMENT_1)
            ->addData([
        'attribute_set_id' => $attributeSetId,
        'attribute_group_id' => $attributeGroupId,
        'used_in_forms' => ['adminhtml_customer', 'customer_account_create', 'customer_account_edit'],
    ]);

    $document->save();
    $setup->endSetup();
}

}

Now i want to set value to this attribute pragmatically.

How can i do achieve this ?

Thanks in advance.

6 Answers 6

11

Check below code is working great for me. Tested with Magento 2.3.3

        $avatar = $this->request->getParam('avatar');
         // \Magento\Customer\Model\Customer $customerModel,
            $customerNew = $this->customerModel->load($this->customerSession->getCustomer()->getId());
            $customerData = $customerNew->getDataModel();
            $customerData->setCustomAttribute('customer_avatar',$customerAvatar);
            $customerNew->updateData($customerData);
            // \Magento\Customer\Model\ResourceModel\CustomerFactory $customerFactory
            $customerResource = $this->customerResourceFactory->create();
            $customerResource->saveAttribute($customerNew, 'customer_avatar');
1
  • 1
    It's working.. Thanks for posting. Commented Apr 6, 2021 at 10:37
11

This may help for you to save the custom attribute.

protected $_customerRepositoryInterface;

public function __construct(
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
    \Magento\Customer\Model\CustomerFactory $customerFactory
) {
    $this->_customerRepositoryInterface = $customerRepositoryInterface;
    $this->_customerFactory = $customerFactory;
}

public function execute()
{
    $customerId = 2; // Corresponding customer id
    $customer = $this->_customerFactory->create()->load($customerId)->getDataModel();
    $customer->setCustomAttribute('custom_attribute_name', 'value');
    $this->_customerRepositoryInterface->save($customer);
}
7
  • Thanks for responding. but this won't work. You are saving attribute with type text, i have image type and need to save from external URL. Commented Sep 5, 2017 at 11:45
  • 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:27
  • 1
    this is working perfect for custom attribute with text type. thanks @sabarivenkatesankrish Commented Sep 24, 2018 at 9:53
  • @SanjayVadadoriya, its not worked for me even i the type is text Commented Dec 11, 2018 at 12:51
  • 1
    this worked great! and using the repository to save the model is the correct way of doing this in Magento2
    – Char
    Commented May 22, 2019 at 11:03
5

To save custom customer attribute

Code Tested in Magento v2.2.1 and it working.

namespace Vendor\Module\Controller\Index;

use Magento\Customer\Model\Customer;
use Magento\Customer\Model\ResourceModel\CustomerFactory as CustomerResourceFactory;
use Magento\Customer\Model\Session as CustomerSession;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;

/**
 * Class Index
 */
class Index extends Action
{
    const CUSTOM_CUSTOMER_ATTR = 'xyz';
    /**
     * @var CustomerResourceFactory
     */
    protected $customerResourceFactory;
    /**
     * @var Customer
     */
    protected $customerModel;
    /**
     * @var CustomerSession
     */
    protected $customerSession;

    /**
     * Index constructor.
     * @param Context $context
     * @param CustomerResourceFactory $customerResourceFactory
     * @param Customer $customerModel
     * @param CustomerSession $customerSession
     */
    public function __construct(
        Context $context,
        CustomerResourceFactory $customerResourceFactory,
        Customer $customerModel,
        CustomerSession $customerSession
    )
    {
        parent::__construct($context);
        $this->customerResourceFactory = $customerResourceFactory;
        $this->customerModel = $customerModel;
        $this->customerSession = $customerSession;
    }

    /**
     * @return \Magento\Framework\App\ResponseInterface
     */
    public function execute()
    {
        /* ********* Start : Important area :  to save custom customer attribute value without losing session on refresh *********** */

        if ($this->customerSession->isLoggedIn()) {
            $customAttributeValue = $this->getRequest()->getParam('custom_attribute'); // it just an example to pull value

            $customerId = $this->customerSession->getCustomer()->getId();

            $customerNew = $this->customerModel->load($customerId);
            $customerData = $customerNew->getDataModel();
            $customerData->setCustomAttribute(self::CUSTOM_CUSTOMER_ATTR, $customAttributeValue);
            $customerNew->updateData($customerData);

            $customerResource = $this->customerResourceFactory->create();
            $customerResource->saveAttribute($customerNew, self::CUSTOM_CUSTOMER_ATTR);

            /* ********* End: Important area :  to save custom customer attribute value without losing session on refresh *********** */

            $this->messageManager->addSuccess(__('You are successfully save the data!!'));
        }
        return $this->_redirect('route/controller/action'); // it just an example for return
    }
}
1

@Developer Webile, Your code in question is invalid (few uses missed and other things). I added missing things. Here is Working code. P.S. Changed const name for better understanding/reading.

<?php

namespace Vendor\ModuleName\Setup;

use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Customer\Model\Customer;
use Magento\Customer\Setup\CustomerSetupFactory as CustomerSetupFactory;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;

class InstallData implements InstallDataInterface
{

    const NEW_ATTRIBUTE_NAME = 'new_attribute_name';
    protected $customerSetupFactory;
    private $attributeSetFactory;


    public function __construct(
        CustomerSetupFactory $customerSetupFactory,
        AttributeSetFactory $attributeSetFactory
    )
    {
        $this->customerSetupFactory = $customerSetupFactory;
        $this->attributeSetFactory = $attributeSetFactory;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

        $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
        $attributeSetId = $customerEntity->getDefaultAttributeSetId();

        $attributeSet = $this->attributeSetFactory->create();
        $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

        $customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, self::NEW_ATTRIBUTE_NAME, [
            'type' => 'varchar',
            'label' => 'Comment for new field',
            'input' => 'image',
            "source" => '',
            'required' => false,
            'default' => '0',
            'visible' => true,
            'user_defined' => true,
            'sort_order' => 210,
            'position' => 210,
        ]);

        $document = $customerSetup->getEavConfig()->getAttribute(\Magento\Customer\Model\Customer::ENTITY, self::NEW_ATTRIBUTE_NAME)
            ->addData([
                'attribute_set_id' => $attributeSetId,
                'attribute_group_id' => $attributeGroupId,
                'used_in_forms' => ['adminhtml_customer', 'customer_account_create', 'customer_account_edit'],
            ]);

        $document->save();
        $setup->endSetup();
    }
}
-1

Load your customer and try this:

$customer->setData('your_option_name', $yourOptionValue);

$customer->save();
1
  • This isn't working alreay tried below. $customer->setMedicalReport($medicalReport); Cause i am getting URL from which i need to save image/pdf. Commented Sep 5, 2017 at 8:15
-1
declare(strict_types=1);
namespace Pranav\CustomerAttribute\Model;

use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Model\CustomerFactory;
class CustomerAttributeUpdate 
{
/**
 * @var CustomerRepositoryInterface
 */
private $customerRepository;
/**
 * @var CustomerFactory
 */
private $customerFactory;

/**
 * @param CustomerRepositoryInterface $customerRepository
 */
public function __construct(
    CustomerRepositoryInterface $customerRepository,
    CustomerFactory $customerFactory
) {
    $this->customerRepository = $customerRepository;
    $this->customerFactory = $customerFactory;
}
public function execute($customer): string
{
   
        $customerId = $customer->getEcommId();
        $customerAdditional = $this->customerFactory->create()->load($customerId);
//if you need to get customer custom attribute 

        $registrationDate = $customerAdditional->getRegistrationDate();
        $renewalDate = $customerAdditional->getRenewalDate();
        $expiryDate = $customerAdditional->getExpiryDate();
        $customerInterface->setCustomAttribute('registration_datetime', $registrationDate);
        $customerInterface->setCustomAttribute('renewal_date', $renewalDate);
        $customerInterface->setCustomAttribute('expiry_date', $expiryDate);
        $this->customerRepository->save($customerInterface);        
}

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.