0

I am trying to send Observer info into the block file. used the add to cart event as like below.

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

Then

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

<?php
 namespace Vendor\Module\Observer;
 class Checkoutcartproductaddafter implements \Magento\Framework\Event\ObserverInterface
 {
  protected $layout;
  public function __construct(
    \Magento\Framework\View\Layout $layout)
   {
    $this->layout = $layout;
   }
  public function execute(\Magento\Framework\Event\Observer $observer)
  {     
    $event = $observer->getEvent();         
    $eventData = $event->getData('quote_item');
    $item = ($eventData->getParentItem() ? $eventData->getParentItem() : $eventData);
    $product = $item->getProduct();
    $productId = $product->getId();
      $prepareJson = array(
             'Added To Cart' => array(
             'productId' => $productId,
             'productName' => $product->getName(),                    
          )
        );
     $block = $this->layout->createBlock('Vendor\Module\Block\Index\Index')->setTemplate('Vendor_Module::before-body-end.phtml')
        ->setObserverData($prepareJson)
        ->toHtml();
     }
   }

Vendor/Module/view/frontend/templates/before-body-end.phtml

<?php 
 $jsonData = $block->getObserverData();
?>
<script id='test_script' type='text/javascript'>
  console.log('inside');
  var data = '<?php echo $jsonData; ?>';
  console.log('--data--',data);
</script>

From the above code I am able to pass the observer data into the phtml file, but I am trying to print the received info into the browser console.

Once printed in browser i have to send to a third party tool using javascript function.

The problem is whatever js is written That's not working. Please help me how can we achieve this. Thanks in Advance!!

8
  • what about the local storage? cart items/info is normally available in it
    – SantiBM
    Oct 28, 2020 at 13:07
  • @SantiBM, yes, this is one event i mentioned above, like that I have to make for all major events in magento2(order. delete cart, invoice, shipment, customer_login) etc.. Oct 28, 2020 at 13:32
  • @SantiBM, please update your answer Oct 29, 2020 at 12:45
  • hi! try this: magento.stackexchange.com/questions/301886/… I'm not sure why you need to use an observer if your goal is to have the data in the console
    – SantiBM
    Oct 29, 2020 at 17:26
  • @SantiBM, bcz i have to send the info to third party tool using javascript. so I am sending data from all the events, that i can get it in phtml, a javascript function is written in phtml to take this data recieved from observer. \ Oct 30, 2020 at 6:37

1 Answer 1

1
+100

define same observer into below event.

   <event name="controller_action_predispatch_catalog_product_view">
       <observer name="send_data2" instance="Vendorename\Modulename\Observer\Yourfilename" />
   </event>
    <event name="checkout_cart_product_add_after">
       <observer name="send_data1" instance="Vendorename\Modulename\Observer\Yourfilename" />
   </event>

Add into your Observer file

protected $resultPageFactory;

public function __construct(
    .............................................................
    \Magento\Framework\View\Result\PageFactory $resultPageFactory,
    .............................................................

) {
    ................................................
    $this->resultPageFactory = $resultPageFactory;
    ...............................................
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
    ob_start();
    $rowData = "your custom data"; // you can add object json array any kind of data
    $resultPage = $this->resultPageFactory->create();

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $cart = $objectManager->get('\Magento\Checkout\Model\Cart');

    // retrieve quote items collection
    $itemsCollection = $cart->getQuote()->getItemsCollection();

    // get array of all items what can be display directly
    $itemsVisible = $cart->getQuote()->getAllVisibleItems();

    $data = [];
    $x = 0;
    foreach($itemsVisible as $item) {
        $data[$x]['name'] = $item->getName();
        $data[$x]['sku'] = $item->getSku();
        $data[$x]['qty'] = $item->getQty();
        $x++;
      }
    $phtml_data = json_encode($data);

    $block = $resultPage->getLayout()
            ->createBlock(\Vendorname\Modulename\Block\CustomBlock::class)
            ->setData('customdata', $phtml_data)
            ->setTemplate("Vendorname_Modulename::customdata.phtml")->toHtml();
    echo $block;
}

Add into your phtml file

<?php
$data = $block->getData('customdata');
print_r($data);
?>

<script type="text/javascript">
console.log("<?php echo $data; ?>");
</script>

I Hope This Helps You.

10
  • Hi @msquare, yes I can get observer data in phtml but the JavaScript written in phtml not working, pls check my question. Nov 3, 2020 at 1:49
  • @jafarpinjar check into console observe data are printed. please check and update me..
    – Msquare
    Nov 3, 2020 at 4:35
  • hi @msquare, yes i checked it, console its not printing Nov 3, 2020 at 9:01
  • i update file please check and update me.
    – Msquare
    Nov 3, 2020 at 9:05
  • Have you checked @jafarpinjar ?
    – Msquare
    Nov 3, 2020 at 9:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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