Adding Customer Attributes in Magento!
Feb 24, 2012 · 1 minute readCategory: php
If you ever need to create a custom field to save data against a customer in Magento you will probably need to create a custom attribute.
Creating the attribute is easy, in your modules install script you do:
<?php
$installer = $this;
$installer->startSetup();
$installer->addAttribute('customer', 'my_custom_attribute', array('type'=>'text'));
$installer->endSetup();
Then on the customer object you can update and save it accordingly:
<?php
$customer = Mage::getModel('customer/customer')->load($customerId);
$customer->setMyCustomAttribute("Some custom data that needs to be saved")->save();
echo Mage::getModel('customer/customer')->load($customerId)->getMyCustomAttribute(); // Outputs 'Some custom data that needs to be saved'
To make your installer work you need to create a folder in the root of your module sql/mymodule_setup
In there create the file mysql4-install-0.1.0.php
And put the above installer code (plus any other install related code) in there.
You also need to add the following to your modules etc/config.xml file
<resources>
<mymodule_setup>
<setup>
<module>EdmondsCommerce_Mymodule</module>
<class>Mage_Sales_Model_Mysql4_Setup</class>
</setup>
<connection>
<use>core_setup</use>
</connection>
</mymodule_setup>
</resources>