1

I need to make a custom customer attribute available as email template variable.

I created the following Observer, that executes just fine.

use Magento\Framework\Event\ObserverInterface;

class AddExtraDataToTransport implements ObserverInterface
{
  public function execute(\Magento\Framework\Event\Observer $observer)
  {
    $transport = $observer->getEvent()->getTransport();
    $order = $transport->getOrder();

    $transport->addData([
       'test' => 'this is a test',
    ]);
  }
}

How would I get ahold of the order's Customer here?

I tried using $order->getCustomer() which returns null. I expected it to return the Customer Object.

After reading the code of Order I expected this to work.

\Magento\Sales\Model\Order Line 46:

* @method \Magento\Customer\Model\Customer getCustomer()

Can anyone point me in the right direction?

1 Answer 1

4

This works:

use Magento\Framework\Event\ObserverInterface;

class AddExtraDataToTransport implements ObserverInterface
{
  public function __construct(
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface
  ){
    $this->_customerRepositoryInterface = $customerRepositoryInterface;
  }

  public function execute(\Magento\Framework\Event\Observer $observer)
  {
    $transport = $observer->getEvent()->getTransport();
    $customer = $this->_customerRepositoryInterface->getById($transport->getOrder()->GetCustomerId());

    $transport->addData([
       'attr' => $customer->getCustomAttribute('attr')->getValue()
    ]);
  }
}

Not sure if this is the easiest way though. Comments are appreciated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.