0

I am using Magento 2.3.5-p2

I am adding a new module to add an Observer that will trigger some js code during an event that happens

below are the file and its content I have added

File Name and Path : app/code/Vendor/MyModule/registration.php

Content :

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Vendor_MyModule',
    __DIR__
); 

File Name and Path : app/code/Vendor/MyModule/etc/module.xml

Content :

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Vendor_MyModule" setup_version="1.0.1">
    </module>
</config>

File Name and Path :

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

Content :

<?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="myObserverNameWishlistAddProduct" instance="Vendor\MyModule\Observer\WishlistAddProduct" />
    </event>
    <event name="wishlist_add_item">
        <observer name="myObserverNameWishlistAddItem" instance="Vendor\MyModule\Observer\WishlistAddItem" />
    </event>
    <event name="wishlist_update_item">
        <observer name="myObserverNameWishlistUpdateItem" instance="Vendor\MyModule\Observer\WishlistUpdateItem" />
    </event>
    <event name="wishlist_product_add_after">
        <observer name="myObserverNameWishlistProductAddAfter" instance="Vendor\MyModule\Observer\WishlistProductAddAfter" />
    </event>
</config>

File Name and Path for Observer to trigger during wishlist add an item :

app/code/Vendor/MyModule/Observer/WishlistAddItem.php

Content :

<?php

namespace Vendor\MyModule\Observer;

use Magento\Framework\Event\ObserverInterface;

class WishlistAddItem implements ObserverInterface
{
  public function __construct()
  {
    // Observer initialization code...
    // You can use dependency injection to get any class this observer may need.
  }
  public function execute(\Magento\Framework\Event\Observer $observer)
  {
    // Observer execution code...
    $myEventData = $observer->getData('myEventData');

    var_dump('wishlist_add_item');die;
  }
}


?>

File Name and Path for Observer to trigger during wishlist product add after

app/code/Vendor/MyModule/Observer/WishlistProductAddAfter.php

Content :

<?php

namespace Vendor\MyModule\Observer;

use Magento\Framework\Event\ObserverInterface;

class WishlistProductAddAfter implements ObserverInterface
{
  public function __construct()
  {
    // Observer initialization code...
    // You can use dependency injection to get any class this observer may need.
  }
  public function execute(\Magento\Framework\Event\Observer $observer)
  {
    // Observer execution code...
    $myEventData = $observer->getData('myEventData');

    var_dump('wishlist_product_add_after');die;
  }
}


?>

the code above is able to work perfectly fine, and I am able to get the below output when adding an item to the wishlist

string(26) "wishlist_product_add_after"

but now I want to add a javascript code when an observer is executed

so instead of var_dump('wishlist_product_add_after')

it will be something like

<script>

dataLayer.push({
'event': 'trackEvent',
'eventDetails.category': 'product search result engagement',
'eventDetails.action': 'add to wish list',
'eventDetails.label': '18 grains dried fruits granola (7 X 40g) X 4 packs',

//product name
'sellingPrice': '103.00', //selling price
'salePrice': '115.20', //sale price
'productID': '1329543075804', //product id
'productName': '18 grains dried fruits granola (7 X 40g) X 4 packs',

//product name
'productCategory': 'grocery', //product category
'marketPrice': '200.00', //market price
'shippingWestMalaysia': '0.00', //shipping fee
'shippingEastMalaysia': '4.00' //shipping fee

});

</script>

how do I add this type of javascript code inside the PHP observable file?

any help would be appreciated

Thank you

1

2 Answers 2

0

You can bind his into event observer by echo statement like this one :

echo '<script>';
echo 'dataLayer.push({';
.......
.......
.......
echo '</script>';
0

I don't think that you will be able to achieve what you want by using php observers. In this particular case, when you press an 'Add to Wishlist' button, a post request is sent. During this request, the mentioned observer events are triggered. And when the request is finished, it returns a 302 redirect to the Wishlist overview page. So if you add some content in your observer, it will not work.

I guess you'd better add a mixin for the vendor/magento/module-wishlist/view/frontend/web/js/add-to-wishlist.js widget. Here is how you can do it:

1. app/code/Vendor/Module/view/frontend/requirejs-config.js

var config = {
    config: {
        mixins: {
            'Magento_Wishlist/js/add-to-wishlist': {
                'Vendor_Module/js/add-to-wishlist-mixin': true
            }
        }
    }
};

2. app/code/Vendor/Module/view/frontend/web/js/add-to-wishlist-mixin.js

define([
    'jquery'
], function ($) {
    'use strict';

    return function (addToWishlistWidget) {
        $.widget('mage.addToWishlist', addToWishlistWidget, {
            _bind: function () {
                this._super();

                var updateWishlist = 'click ' + this.options.actionElement,
                    additionalEvents = {};

                additionalEvents[updateWishlist] = 'updateDataLayer';

                this._on(additionalEvents);
            },

            updateDataLayer: function () {
                if (dataLayer) {
                    dataLayer.push({
                        // ...
                        // event info here
                        // ...
                    });
                }
            }
        });

        return $.mage.addToWishlist;
    };
});
1
  • can you help explain on how this code works, I try putting console.log at certain line, apparently the code inside _bind: function() { are triggered when user refresh on the page, I tried console.log inside updateDataLayer but seems like it is not read when I try adding item to wishlist Nov 23, 2021 at 6:54

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.