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 vendor\module\Block;
class SaveData
{
protected $customer;
protected $customerRepository;
public function __construct(
\Magento\Customer\Model\Customer $customer,
\Magento\Customer\Api\CustomerRepositoryInterface $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('\vendor\module\Block\SaveData');
$blockPHPCuong->saveDatagruppo();
How can I do so that I can save my attribute on page load? Thanks