3

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.

7

Check below code is working great for me.

        $avatar = $this->request->getParam('avatar');

            $customerNew = $this->customerModel->load($this->customerSession->getCustomer()->getId());
            $customerData = $customerNew->getDataModel();
            $customerData->setCustomAttribute('customer_avatar',$customerAvatar);
            $customerNew->updateData($customerData);

            $customerResource = $this->customerResourceFactory->create();
            $customerResource->saveAttribute($customerNew, 'customer_avatar');
7

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);
}
  • 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. – Developer Webile Sep 5 '17 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. – Purushotam Sharma Mar 28 '18 at 13:27
  • this is working perfect for custom attribute with text type. thanks @sabarivenkatesankrish – Sanjay Vadadoriya Sep 24 '18 at 9:53
  • @SanjayVadadoriya, its not worked for me even i the type is text – jafar pinjar Dec 11 '18 at 12:51
  • this worked great! and using the repository to save the model is the correct way of doing this in Magento2 – Char May 22 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
    }
}
0

@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();
  • This isn't working alreay tried below. $customer->setMedicalReport($medicalReport); Cause i am getting URL from which i need to save image/pdf. – Developer Webile Sep 5 '17 at 8:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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