Using Custom Customer Variables in Transactional Email Templates in Magento
Introduction
In Magento, you can easily add custom variables to your customer attributes using the EAV (Entity Attribute Value) model. Once added, these variables can be used to personalize transactional email templates for a more engaging customer experience. In this post, we’ll guide you through adding a custom attribute to the customer entity and using it in an email template.
Adding a Custom Variable to Customer
We’ve already seen how to add a custom variable named ‘companyname’ to our customer in the provided code snippet:
$setup->addAttribute(
'customer',
'companyname',
array(
'input' => 'text',
'type' => 'varchar',
'label' => 'Company name',
'visible' => 1,
'required' => 1,
'user_defined' => 1,
)
);
$setup->addAttributeToGroup(
$entityTypeId,
$attributeSetId,
$attributeGroupId,
'companyname',
'999'
);
// Save the attribute
$oAttribute = Mage::getSingleton('eav/config')->getAttribute('customer', 'companyname');
$oAttribute->setData('used_in_forms', array('adminhtml_customer','customer_account_create'));
$oAttribute->save();
Using the Custom Variable in an Email Template
Now, let’s use this custom variable in a transactional email template. The code snippet provided attempts to do just that:
{{var order.getCustomer().getCompanyname()}}
However, it seems you’re running into an issue where the variable isn’t being recognized or displayed in the email.
Resolving the Issue
The error lies in how we’re trying to access the custom attribute. In Magento 2, the correct way to get a customer’s attribute is by using the getExtensionAttributes() method:
{{var order.getData('extension_attributes').customer.getCompanyname()}}
This updated code snippet correctly retrieves the customer object from the order data and then accesses the ‘companyname’ attribute.
Conclusion
Adding custom variables to your customer entities in Magento is a powerful way to personalize transactional emails. By following the steps outlined above, you can easily extend the customer entity with new attributes and use them in email templates for a more engaging customer experience.
Remember, always ensure that the customer attribute you’re trying to access exists in the template context. If your custom variable isn’t recognized, double-check if it has been properly added and saved using the Magento installation process or via an upgrade script.
For further details on working with transactional emails in Magento 2, I recommend checking out Laravel Company’s guide on Magento 2 email templates.