Score:0

Attach JavaScript to page with Commerce Events

gg flag

I'm using hook_page_attachments_alter in Drupal 9 to add some JavaScript dataLayer calls to certain routes, but I also need to add some to certain cart events (i.e. add item to cart).

I've written a CartEventSubscriber that listens for cart events and have one responding to the AddToCart event, but the only variable it exposes is CartEntityAddEvent $event.

Is there another way to tell from hook_page_attachments_alter or some other hook that I'm on a page that resulted from the Add to Cart click so that I can add this JS there?

Thanks!

Jaypan avatar
de flag
You would attach the file to something on the page - a form, a node, or some other object. If it's a form, you can use hook_form_alter(), and attach your library with the `#attached` key of the form render array.
Delford Chaffin avatar
gg flag
But how do I know it's only AFTER the item has been added to the cart? There is the Add To Cart form I could attach it to and I tried that form's `isSubmitted()` method, but it is always false due to the way that form redirects back to the page, I assume.
Score:0
gg flag

So, I found the GA Push module, but it wasn't sure how fully it was being maintained, but I may revisit it in the future. But for my purposes for now, I just took inspiration from the way they use session objects. So, my AddToCart method ended up looking like ...

public function addToCart(CartEntityAddEvent $event) {
  /** @var \Drupal\commerce_product\Entity\ProductVariationInterface $product_variation */
  $product_variation = $event->getEntity();
  $request = $this->requestStack->getCurrentRequest();
  $session = null;
  if($request->hasSession()){
    $session = $request->getSession();
  }
  if(is_null($session)){
    return;
  }
  $session->set('{session_id}}', {js_snippet});
}

And in my .module file's hook_page_attachments_alter function, I added ...

if(\Drupal::request()->hasSession()){
  $session = \Drupal::request()->getSession();
  attachments[] = $session->get('{session_id}');
  $session->remove('{session_id}');
}

And proceeded to attach the snippets as normal.

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.