Posted on

Save customer attribute programmatically in Magento 2

I’m trying to save the value of some custom customer attributes programmatically.

I have seen a few examples and everyone is proposing to create a controller for this. But I would like to save the attribute value without creating a controller and without calling it from the Object Manager.

In Magento 1 the code was this and it was enough to reload the page for it to work:

$customer = Mage::getSingleton(‘customer/session’)->getCustomer()

In my Magento 2 this is my code that i tried but not work:

namespace vendormoduleBlock;

class SaveData

protected $customer;

protected $customerRepository;

public function __construct(
MagentoCustomerModelCustomer $customer,
MagentoCustomerApiCustomerRepositoryInterface $customerRepository
$this->customer = $customer;
$this->customerRepository = $customerRepository;

public function saveDatagruppo()
$customer_id = 3;

$customer_repo = $this->customerRepository->create();
$customer = $customer_repo->getById($customer_id);

// get Custome Attribute value
$cust_att = $customer->getCustomAttribute(“datagruppo”)->getValue();

//set custom Attribute value
$add_id = “2021”;


And this is the code in frontend

$blockPHPCuong = $block->getLayout()->createBlock(‘vendormoduleBlockSaveData’);

How can I do so that I can save my attribute on page load?

Leave a Reply

Your email address will not be published.