Magento 2.2 – How to Get Customer Custom Attribute Value in Observer

event-observermagento2.2

I have created a customer custom attribute like(gst_no).
In my Observer where I get my customer data I want to get the value of this attribute too.

 $order = $observer->getEvent()->getOrder();
 $order_id = $order->getIncrementId();
 $shippingAddress = $order->getShippingAddress(); // shipping address
 $email = $shippingAddress->getEmail();
 $customer = $order->getCustomer();
 $customer_id = $order->getCustomerId();
 $gstno = $customer->getResource()->getAttribute('gst_no')->getFrontend()->getValue($customer);
 $order->setGstNo($customer_id);
 $order->save();

But I am not getting attribute value.,can anyone help?

Best Answer

Try to use this below code :

/**
 *  @var \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface
 *  @var \Magento\Sales\Model\Order $order
*/
protected $_customerRepositoryInterface;
protected $_order;

public function __construct(
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
    \Magento\Sales\Model\Order $order,
)
{
    $this->_customerRepositoryInterface = $customerRepositoryInterface;
    $this->_order = $order;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{ 
    $order = $observer->getEvent()->getOrder();
    $orderdetails = $this->_order->load( $order->getId());
    $customerId = $orderdetails ->getCustomerId();
    $customeratt = $this->_customerRepositoryInterface->getById($customerId);
    $cattrValue = $customeratt->getCustomAttribute('gst_no');
}