0

I need to be able to hide the add to cart button of certain products are already in the cart.

I have Full Page Cache turned on so it seems to cant access the checkout session.

What would be the best approach to take on this?

2

Can you tell me more about your requirements? Does it really need to be hidden? I'm asking because there can be a better, more UX friendly solution for that.

Now I can only say that you are right about FPC (Full Page Cache).

You have to use javascript to get user private data. Please look into files from Magento_Catalog module:

  • addtocart.phtml
  • validate-product.js

You see that by default add to cart button is disabled and then when validate-product.js is triggered it makes button enabled.

What you could is to hide this button by default (css class, etc.) and show it only if specific product hasn't been already added to cart.

How to extend validate-product.js widget https://devdocs.magento.com/guides/v2.4/javascript-dev-guide/javascript/js_mixins.html#extend-jquery-widget

How to check if product is already in cart?

When extending validate-product.js you can use Magento_Customer/js/customer-data to get information about items in cart.

Example how you can use customer-data in some other js module.

define([
    'someOtherDependency1'
    'Magento_Customer/js/customer-data',
    'someOtherDepedency2'
], function (dep1, customerData, otherDep2) {
    'use strict';

    // some code

    // get cart items
    var cartData = customerData.get('cart'),
      items = cartData().items;

    // subscribe for cart data changes
    cartData.subscribe(function (updatedCart) {
      
    }

    // rest of code
});

Let me know if that is enough or you will need more guidance on that. I recommend also to look into core code of Magento and look for cartData or .get('cart') so you can find examples and learn.

| improve this answer | |
  • Thanks for this, it helped massively. – Goose84 Oct 20 at 7: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.