Magento 2 stores being the preferred choice for the majority of the E-commerce business of various types, developers have to be ready to implement any functionalities out of the blue!
One such thing that I faced was in a B2B Magento 2 store development. The B2B registration status value was required to send the registration acknowledgment or rejection Email to the customers. For that, I wanted to get the value of custom customer attribute “Account Status”. Hence, I came up with the below solution.
In other cases where you would want to get custom customer attribute value in Magento 2 stores is integration with 3rd party APIs. The APIs would return the customer attributes value which is not the part of the default Magento 2 and you’d want to use them further and require these custom attributes values. Another solution that becomes essential in this context is get customer data from attribute value in Magento 2. This approach provides the necessary tools to efficiently extract customer data linked to specific attribute values, particularly when sourced from external APIs.
Method to get custom customer attribute value in Magento 2:
<?php namespace [Vendor]\[Module]\Helper; use Magento\Framework\App\Helper\Context; use Magento\Customer\Api\CustomerRepositoryInterface; class Data extends AbstractHelper { protected $customerRepository; public function __construct( Context $context, CustomerRepositoryInterface $customerRepository) { $this->customerRepository = $customerRepository; parent::__construct($context); } public function getAttributeValue($customerId) { $customer = $this->customerRepository->getById($customerId); return $customer->getCustomAttribute('custom_attribute_code'); } }
That’s it.
Likewise you can also create custom order attribute in Magento 2 which will be seen in the admin grid, as order information is used to manage and fulfill online orders efficiently.
Feel free to share the post with fellow developers on social media.
Recommended Read: Learn to Add Extra Fee in Magento 2