What is the most efficient way (using Magento methods) to load just a customer attribute, changing its value and saving it.
2 Answers
If you already have the customer model (at least partially loaded), you can use this line to save a single attribute:
$customer->getResource()->saveAttribute($customer, 'attribute_code_goes_here');
Actually, for this to work, the only attributes that must be present in the $customer
instance are entity_id
and the attribute that you want to save. You can load the customer with only selected EAV attributes like this:
$customer = Mage::getModel('customer/customer')
->load($customerId, array('attribute_code_goes_here'));
-
apologies for taking so long to mark it as correct, was just reviewing my questions and saw this– pzirkindDec 20, 2015 at 0:33
$customer = Mage::getModel('customer/customer')->loadByEmail('[email protected]');
//or if you know the customer ID
$customer = Mage::getModel('customer/customer')->load($id, array('attribute_code'));
// attribute_code
$customer->setAttributeCode('new value here')->save();
This will save only the value changed. Magento strips out all non changed elements and only saves what has been changed from the data.
It does this in: Mage_Eav_Model_Entity_Abstract::_collectSaveData()
which is a parent of Mage_Customer_Model_Resource_Customer
, which handles saving functionality.