6

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?

Mir
  • 466
  • 6
  • 20
  • 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 https://magento.stackexchange.com/questions/112948/magento-2-how-do-customer-sections-sections-xml-work – 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

1 Answers1

9

You need to create a plugin in order to save customer email to the local storage. So, add a frontend 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\Plugin\AddCustomerEmail" />
    </type>
</config>

And the plugin will look like this:

<?php

namespace Your\Module\Plugin;

use Magento\Customer\Helper\Session\CurrentCustomer;

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

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

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

    return $result;
}

}

More information can be found in a similar question here.

Roman Snitko
  • 786
  • 5
  • 15