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()
$customer->setmyattribute(date(‘Y’));
$customer->save();

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();
print_r($cust_att);

//set custom Attribute value
$add_id = “2021”;
$customer->setCustomAttribute(“datagruppo”,$add_id);
$customer_repo->save($customer);

}
}

And this is the code in frontend

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

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

Leave a Reply

Your email address will not be published.