1

I need to send data to an external API when a customer (I mean a logged in customer) add a product to wishlist.

I found the event: wishlist_add_product.

$this->_eventManager->dispatch(
    'wishlist_add_product',
    ['wishlist' => $wishlist, 'product' => $product, 'item' => $result]
);

This event is not related to a customer, this is also triggered when a guest user add a product to wishlist.

In my Observer I have to check if the user is logged in, then I have to load some customer details and I can call the API.

The question is:

How do I get the customer ID if it is authenticated, when the customer object is not present in the dispatch?

app/code/Vendor/Module/etc/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="wishlist_add_product">
        <observer name="my_wishlist_add_product" instance="Vendor\Module\Observer\MyObserver" />
    </event>
</config>

app/code/Vendor/Module/Observer/MyObserver.php

<?php
namespace Vendor\Module\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class MyObserver implements ObserverInterface{
    public function execute(Observer $observer){
        // here I need something for load the logged in customer (if it is logged in)
    }
}
  • you can use Customer Model Session to get the logged in customer id irrespective of the fact that the customer object is not in the dispatched event. You can find the module added below for your reference, which gets the logged in customer id when the customer adds the products to the wishlist. – Haijerome Feb 8 at 13:16
3

You can use and inject Magento\Customer\Model\Session in your observer class to get the logged in Customer Id. It doesn't matter whether the dispatched method has customer object, you can use this customer model session class to get the customer object.

Your observer should be like this

app/code/StackExchange/WishlistCustomer/Observer/WishlistAddItem.php

<?php
/**
 *   StackExchange_WishlistCustomer
 *   Jerome Dennis <haijerome@gmail.com>
 */

namespace StackExchange\WishlistCustomer\Observer;

use Magento\Customer\Model\Session as CustomerSession;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Message\ManagerInterface;
use Psr\Log\LoggerInterface;

/**
 * Class WishlistAddItem
 * @package StackExchange\WishlistCustomer\Observer
 */
class WishlistAddItem implements ObserverInterface
{

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    /**
     * @var \Magento\Customer\Model\Session
     */
    protected $customerSession;

    /**
     * @var \Magento\Framework\Message\ManagerInterface
     */
    protected $messageManager;

    /**
     * @param CustomerSession $customerSession
     * @param WishlistFactory $wishlistFactory
     * @param ManagerInterface $messageManager
     * @param \Psr\Log\LoggerInterface $logger 
     */
    public function __construct(
        CustomerSession $customerSession,
        ManagerInterface $messageManager,
        LoggerInterface $logger
    ) {
        $this->customerSession = $customerSession;
        $this->messageManager = $messageManager;
        $this->logger = $logger;
    }

    /**
     * @param Observer $observer
     * @return void
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     */
    public function execute(Observer $observer)
    {
        $request = $observer->getEvent()->getRequest();
        // checks customer is logged in 
        if ($this->customerSession->isLoggedIn()) {
            // gets the logged in customer id from thje customer session model
            $customerId = $this->customerSession->getCustomerId();
            // customer id will be in debug.log
            $this->logger->info('Logged In Customer Id ('.__METHOD__.'): '.$customerId);
            //echo '<br/>$customerId : ' . $customerId;exit;
            return $this->customerSession->getCustomerId();
        }
    }
}

app/code/StackExchange/WishlistCustomer/etc/frontend/events.xml

<?xml version="1.0"?>
<!--
/**
 *   StackExchange_WishlistCustomer
 *   Jerome Dennis <haijerome@gmail.com>
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="wishlist_add_item">
        <observer name="wishlist" instance="StackExchange\WishlistCustomer\Observer\WishlistAddItem" />
    </event>
</config>

app/code/StackExchange/WishlistCustomer/etc/module.xml

<?xml version="1.0"?>
<!--
/**
 *   StackExchange_WishlistCustomer
 *   Jerome Dennis <haijerome@gmail.com>
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="StackExchange_WishlistCustomer" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Wishlist"/>
        </sequence>
    </module>
</config>

app/code/StackExchange/WishlistCustomer/registration.php

<?php
/**
 *   https://magento.stackexchange.com/questions/303499/how-to-get-customer-from-observer-in-magento-2
 * 
 *   StackExchange_WishlistCustomer
 *   Jerome Dennis <haijerome@gmail.com>
 */

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'StackExchange_WishlistCustomer',
    __DIR__
);
| improve this answer | |
  • Thank you! Exactly what I need – Francesco Mineo Feb 8 at 13:23
  • Con piacere... glad it helps ! – Haijerome Feb 8 at 13:29
0

Add This line in events.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
   <event name="wishlist_add_item">
       <observer name="MyObserverName" instance="Vendor\Module\Observer\MyObserver" />
   </event>
</config>

this observer file run before this wishlist redirect to wishlist page.

In your MyObserver.php first check if customer is login or not and then your logic.

<?php

namespace Vendor\Module\Observer;

use Magento\Framework\Event\ObserverInterface;

class MyObserver implements ObserverInterface
{
    protected $customerSession;

    public function __construct(
        .................................................
        .................................................
        \Magento\Customer\Model\SessionFactory $customerSession,
        .................................................
        .................................................
    ) {
        .................................................
        .................................................
        $this->_customerSession = $customerSession->create();
        .................................................
        .................................................
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        if ($this->_customerSession->isLoggedIn()) {
            $cusomerid =  $this->_customerSession->getId();
            print_r($cusomerid);
            exit();
        }
    }
}

I Hope This Helps You.

| improve this answer | |
  • This event is triggered when a user go to the wishlist page too, not only when a user add a product to the wishlist. However, this answer not answer to my question. I already found the event I need to use. I want to know how to get the logged in customer. – Francesco Mineo Feb 8 at 13:05
  • Answer Upadate for customer login – Msquare Feb 8 at 18:21

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.