3

I need to get the customer email in homepage in a script.

Googling around I find mentions of window.customerData variable, but is always undefined (perhaps removed in latest versions?)

So at first I tried this:

require([
    'Magento_Customer/js/model/customer',
...

but it fails with error:TypeError: can't convert undefined to object somewhere in customer-addresses.js

Then I tried with:

require([
    'Magento_Customer/js/customer-data',
...

and then customerData.get('customer') but it gives me only first and last name or an empty object (even when the user is logged).

Is there a way to obtain the logged user email anywhere outside the checkout page?

  • have you find a way to retrieve customer email via js? – LucScu Sep 12 '17 at 10:38
  • @LucaS Not out of the box. I ended up creating a new section to be called from customerData.get('myCustomSection') with the info I needed. – Mir Sep 12 '17 at 11:01
  • great, i need to retrieve it too, could you answer with your entire solution? – LucScu Sep 12 '17 at 13:34
  • 1
    @LucaS probably this will help magento.stackexchange.com/questions/112948/… – Mir Sep 12 '17 at 13:39
  • sure thx! but your question remains open try to close it :) – LucScu Sep 12 '17 at 14:58
4

You need to create a plugin in order to save customer email to the local storage. So, add plugin configuration in di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Customer\CustomerData\Customer">
        <plugin name="additional_section_data" type="Your\Module\Model\Plugin\CustomerData" />
    </type>
</config>

And the plugin will look like this:

<?php

namespace Your\Module\Model\Plugin;

use Magento\Customer\Helper\Session\CurrentCustomer;

class CustomerData
{
    /**
     * @var CurrentCustomer
     */
    private $currentCustomer;

    public function __construct(
        CurrentCustomer $currentCustomer
    ) {
        $this->currentCustomer = $currentCustomer;
    }

    public function afterGetSectionData(\Magento\Customer\CustomerData\Customer $subject, $result)
    {
        if ($this->currentCustomer->getCustomerId()) {
            $customer = $this->currentCustomer->getCustomer();
            $result['email'] = $customer->getEmail();
        }

        return $result;
    }
}

More information can be found in a similar question here.

  • Thank you, I ended up by doing something very similar: a custom data section. – Mir Nov 14 '17 at 15:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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