How to get a custom customer attribute on the frontend
-
12-12-2019 - |
Question
I added an extra customer attribute using this code:
$installer->startSetup();
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$entityTypeId = $setup->getEntityTypeId('customer');
$attributeSetId = $setup->getDefaultAttributeSetId($entityTypeId);
$attributeGroupId = $setup->getDefaultAttributeGroupId($entityTypeId, $attributeSetId);
$installer->addAttribute("customer", "province", array(
"type" => "varchar",
"backend" => "",
"label" => "province",
"input" => "multiselect",
"source" => 'eav/entity_attribute_source_table',
"visible" => true,
"required" => false,
"default" => "",
"frontend" => "",
"unique" => false,
"note" => "province",
'option' =>
array (
'values' =>
array (
0 => 'Rome',
1 => 'Milan',
2 => 'Florence',
3 => 'Naples',
),
),
));
$attribute = Mage::getSingleton("eav/config")->getAttribute("customer", "province");
$setup->addAttributeToGroup(
$entityTypeId,
$attributeSetId,
$attributeGroupId,
'province',
'999' //sort_order
);
$used_in_forms=array();
$used_in_forms[]="adminhtml_customer";
$used_in_forms[]="checkout_register";
$used_in_forms[]="customer_account_create";
$used_in_forms[]="customer_account_edit";
$used_in_forms[]="adminhtml_checkout";
$attribute->setData("used_in_forms", $used_in_forms)
->setData("is_used_for_customer_segment", true)
->setData("is_system", 0)
->setData("is_user_defined", 1)
->setData("is_visible", 1)
->setData("sort_order", 100)
;
$attribute->save();
$installer->endSetup();
It works fine in the backend. How to show it in customer frontend dashboard? thanks
Solution
This requires some templating work.
The customer account dashboard page gets rendered by the following file: '/app/design/frontend/base/default/template/customer/account/dashboard/info.phtml'
When you want to get a custom customer attribute here you have to call it by it's code
<?php echo $this->escapeHtml($this->getCustomer()->getProvince()) ?>
ps: Never edit the base template files directly. Make a seperate theme inside default theme package, or make your own theme package :)
OTHER TIPS
Copy below code to get customer attribute option value:
//Get current customer
$customer = Mage::getSingleton('customer/session')->getCustomer();
//Get attribute id
$attrId = $customer->getData('customer_attribute_code');
$attr = $customer->getResource()->getAttribute('customer_attribute_code');
//Get attribute option value
echo $attrValue = $attr->getSource()->getOptionText($attrId);