0

I'm trying to execute some javascript code and pass to it some values after an event (e.g. Add to Cart event) is triggered. To be more specific I'd like to pass:

  • All logged customer details (Firstname, Lastname, Email, etc.)
  • Cart details (Product ID, Product Name, amount, price, etc.)

In order to do that, I create my own module like this:

Vendor/Module/registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Vendor_Module',
    __DIR__
);

Vendor/Module/etc/module.xml

<?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_Module" setup_version="1.0.0.0" active="true" />
</config>

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="checkout_cart_save_after"> 
      <observer name="checkout_cart_save_after" instance="Vendor\Module\Observer\AddToCart" /> 
   </event>
</config>

...and here I don't know how to move forward...

Vendor/Module/Observer/AddToCart.php

<?php

    namespace Vendor\Module\Observer;
 
    use Magento\Framework\Event\ObserverInterface;
    use Magento\Framework\App\RequestInterface;
 
    class AddToCart implements ObserverInterface
    {
        public function execute(\Magento\Framework\Event\Observer $observer) {

        }
 
    }

I think I should get cart and customer details in some way, then pass them to a view (E.g. Vendor/Module/view/frontend/templates/add_to_cart.pthml) and execute inside it my Javascript code. Am I wrong? How should I proceed?

  • try this magento.stackexchange.com/a/325623/82670 – Msquare Nov 11 '20 at 7:20
  • @Msquare thanks, I already saw that answer but I honestly don't understand exactly how to do. Could you elaborate better the answer? – KaMZaTa Nov 11 '20 at 11:52
  • Rather than try and load JS after you add to cart with PHP, why not just use JS to add to cart to begin with? – Ben Crook Nov 11 '20 at 12:59
  • @BenCrook I don't know. Maybe it could be better than this approach. Could you show me how? – KaMZaTa Nov 11 '20 at 13:56
  • @Msquare I don't have any block in my module. Following that example it says: $block = $resultPage->getLayout() ->createBlock(\Vendorname\Modulename\Block\CustomBlock::class) ->setData('customdata', $phtml_data) ->setTemplate("Vendorname_Modulename::customdata.phtml")->toHtml();. Where should I point ->createBlock(\Vendorname\Modulename\Block\CustomBlock::class)? – KaMZaTa Nov 11 '20 at 14:02

Your Answer

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

Browse other questions tagged or ask your own question.