
Collecting relevant customer information is the key to delivering personalized experiences to eCommerce customers. Collecting this data can be pretty exhausting if you don’t have the right tools in place. That’s where the application of customer attributes comes into play. You can get customer custom attribute value in Magento 2 in different ways depending on your use case.
Through this blog, we will discuss the most common methods for this purpose.
What Are Magento 2 Customer Attributes?
First, it's essential to understand how Magento 2 handles customer attributes. Magento utilizes the Entity-Attribute-Value (EAV) model for customer data, enabling flexible attribute management without requiring database schema changes. This architectural approach offers significant advantages over traditional relational database structures, allowing the dynamic creation and modification of attributes without affecting the core database schema.
The Mageto EAV model consists of three main components: entities (such as customers), attributes (the data fields), and values (the actual data stored within these fields). This separation allows for unprecedented flexibility in managing customer information while maintaining data integrity and system performance.
Custom customer attributes can be categorized into several types:
Here are the types of custom customer attributes that you need to know.
Text-based Attributes:
-
Text fields (varchar, text) for storing short and long text values
-
Rich text areas for formatted content
-
Multiline text fields for addresses or detailed descriptions
Numeric Attributes:
-
Integer values for counts, IDs, or whole numbers
-
Decimal values for monetary amounts or precise measurements
-
Float values for calculations requiring decimal precision
Date and Time Fields:
-
Date fields for birthdays, registration dates, or milestones
-
DateTime fields for precise timestamps
-
Time fields for specific time preferences
Selection Attributes:
-
Single-select dropdowns for predefined options
-
Multi-select fields for multiple-choice selections
-
Radio buttons for exclusive selections
-
Checkboxes for boolean or multiple selections
File and Media Attributes:
-
File upload fields for documents or certificates
-
Image upload capabilities for profile pictures
-
Document storage for contracts or agreements
Boolean Fields:
-
Yes/No toggles for preferences
-
True/False values for status indicators
-
Binary choices for feature activation
These attributes are intelligently distributed across multiple database tables based on their data type, ensuring optimal storage and retrieval performance:
-
customer_entity_varchar
for text values and short strings -
customer_entity_int
for integers and boolean values -
customer_entity_datetime
for date and time information -
customer_entity_text
for large text fields and descriptions -
customer_entity_decimal
for decimal and monetary values
In the next section, we shall shed light on the methods to get custom customer attribute in Magento 2.
Methods to Get Custom Attribute Value in Magento 2?
Here are the different methods to get custom attribute value in Magento 2.
1. Using Customer Repository
The Customer Repository is the most robust and future-proof method for accessing customer attributes in Magento 2. This approach follows Magento's service contract pattern, handling the complexity of the EAV model automatically.
<?php
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
class YourClass
{
protected $customerRepository;
public function __construct(
CustomerRepositoryInterface $customerRepository
) {
$this->customerRepository = $customerRepository;
}
public function getCustomerAttributeValue($customerId, $attributeCode)
{
try {
$customer = $this->customerRepository->getById($customerId);
$customAttribute = $customer->getCustomAttribute($attributeCode);
if ($customAttribute) {
return $customAttribute->getValue();
}
return null;
} catch (NoSuchEntityException $e) {
return null;
}
}
}
2. Using Customer Session (Frontend)
When working in the frontend context with logged-in customers, the customer session provides direct access to attribute values.
<?php
use Magento\Customer\Model\Session;
class YourClass
{
protected $customerSession;
public function __construct(Session $customerSession)
{
$this->customerSession = $customerSession;
}
public function getCurrentCustomerAttributeValue($attributeCode)
{
if ($this->customerSession->isLoggedIn()) {
$customer = $this->customerSession->getCustomer();
return $customer->getData($attributeCode);
}
return null;
}
}
3. Using Customer Factory
The Customer Factory is part of Magento's factory pattern implementation, providing a clean way to instantiate customer objects without directly calling the constructor. It's primarily used through dependency injection and helps manage customer data models. Here’s how you can use it to create custom attributes:
<?php
use Magento\Customer\Model\CustomerFactory;
class YourClass
{
protected $customerFactory;
public function __construct(CustomerFactory $customerFactory)
{
$this->customerFactory = $customerFactory;
}
public function getCustomerAttributeValue($customerId, $attributeCode)
{
$customer = $this->customerFactory->create()->load($customerId);
if ($customer->getId()) {
return $customer->getData($attributeCode);
}
return null;
}
}
4. In Template Files (.phtml)
For frontend display, you'll often need to access customer attributes directly in template files:
<?php
// In a .phtml template file where $customer object is available
$attributeValue = $customer->getCustomAttribute('your_attribute_code');
if ($attributeValue) {
echo $attributeValue->getValue();
}
// Or using the getData method
echo $customer->getData('your_attribute_code');
?>
5. Using Object Manager
The Object Manager is Magento 2's central dependency injection container that manages object creation, instantiation, and dependency resolution throughout the application. It facilitates the creation of custom attributes by managing the dependencies and object creation required for custom attribute functionality. At the same time, the EAV system provides a flexible foundation for storing and retrieving these custom values. Take a look at the codes below:
<?php
// Only for testing - avoid in production code
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerRepository = $objectManager->create('Magento\Customer\Api\CustomerRepositoryInterface');
try {
$customer = $customerRepository->getById($customerId);
$attributeValue = $customer->getCustomAttribute('your_attribute_code');
if ($attributeValue) {
return $attributeValue->getValue();
}
} catch (\Exception $e) {
// Handle exception
}
6. Using Resource Model for Performance
Use this method for bulk operations or when you require improved performance.
<?php
use Magento\Framework\App\ResourceConnection;
class YourClass
{
protected $resourceConnection;
public function __construct(ResourceConnection $resourceConnection)
{
$this->resourceConnection = $resourceConnection;
}
public function getCustomerAttributeValue($customerId, $attributeCode)
{
$connection = $this->resourceConnection->getConnection();
$tableName = $this->resourceConnection->getTableName('customer_entity_varchar'); // or appropriate table
$select = $connection->select()
->from($tableName, ['value'])
->where('entity_id = ?', $customerId)
->where('attribute_id = ?', $this->getAttributeId($attributeCode));
return $connection->fetchOne($select);
}
}
Best Practices to Get Customer Attribute Value in Magento 2
-
Error Handling: Always include proper error handling, especially when dealing with customer data that might not exist.
-
Performance: For frontend usage, consider caching the attribute values if they're accessed frequently.
-
Custom Attributes vs. EAV Attributes: Ensure your custom attribute is appropriately set up in the customer EAV system before attempting to retrieve it.
As already mentioned, the Customer Repository method (Method 1) is generally the best approach as it's clean, follows Magento 2 architecture patterns, and handles the complexity of the EAV system automatically. In addition to the six methods mentioned above, you can also utilize the Magento 2 extension from MageDelight. By installing MageDelight’s Magento 2 Custom Attributes extension, you can easily create an unlimited number of attributes and efficiently collect all the required information from the customers.
MageDelight’s Customer Attributes Extension
Here are the features of our Customer attributes extension.
Feature Highlights
-
Easy GUI to make the process easier to create customer attributes
-
A separate section to manage the information given by the customer
-
Manage customer attributes from the admin panel
Extension Key Features
Unlimited Customer Attributes
With MageDelight’s Customer Attribute Extension, you can not only create customer attributes without any limitations but also add extra fields to customer registration forms. It helps store owners collect the maximum necessary information of potential customers.
Easy Graphical User Interface
The Graphical User Interface in the Magento 2 Customer Attributes Extension simplifies the implementation process, thereby attracting a maximum number of customers.
Various Input Validation for Each Attribute
Magento 2 Custom Attributes extension offers various options for input validation for each attribute. You get input validations like numeric, alphanumeric, alpha, URL, etc.
Advantages of Using Magento 2 Custom Attributes Extension
The advantages of MageDelight’s Magento 2 Custom Attributes Extension can be viewed from two perspectives: 1) from the admin point of view and 2) from the customer point of view.
Benefits For The Admin
-
Easy GUI to make the process easier and attractive
-
A separate section to manage the information given by the customer
-
Manage customer attributes from the admin panel
-
Configure meaningful attributes
-
Set a default value for the attributes
-
Set the sort order while creating the attributes
-
Manage attribute options for each store view
-
Manage Customer Group Specific Attributes
Benefits For The Customer
-
Provide inputs from Storefront
-
Manage Attribute Values from My accounts
How to Get Custom Attribute Value in Magento 2: Easy Steps
Implementation of MageDelight’s Custom Attribute Extension involves two easy steps as follows:
-
Install Magento 2 Customer Attributes extension
-
Unzip the extension package file into the root folder of your Magento 2 installation
-
Connect to the SSH console of your server
-
Navigate to the root folder of your Magento 2 setup
-
Run the command as per the below sequence
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy
php bin/magento cache:clean
-
Log out from the backend and log in again
-
Verify these settings to ensure the installation works properly.
-
Click the Add New Attribute button at the top of the admin panel to insert a new customer attribute
Wrapping Up
The key to effectively executing custom attributes in Magento 2 is selecting the appropriate method according to your specific use case, while maintaining code quality, optimizing performance, and ensuring future compatibility. Your chosen approach should enable seamless handling of custom customer attributes across your Magento 2 application, whether working with core functionality or third-party Magento 2 extensions.
Consider factors such as development complexity, performance requirements, maintenance overhead, and team expertise when selecting implementation methods. The Customer Repository approach remains the recommended solution for most scenarios due to its robustness and future-proofing characteristics.
For organizations that require user-friendly attribute management without extensive development resources, solutions like MageDelight's Custom Attributes Extension offer excellent alternatives, combining functionality with ease of use.
If you need assistance with implementing custom customer attributes in your Magento 2 store, consider consulting with experienced Magento developers who can provide guidance tailored to your specific requirements and business objectives.