Set Value to Created Customer Custom Attribute in Magento 2

custom-attributescustomermagento2

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.

Best Answer

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');
Related Topic