1

I know how to extend the catalogAddToCart function and already successfully fired my codes when I go into product detail page and press Add To Cart button. But I still has a problem: how can I get the product details on the product to be added into cart, like SKU? Currently I use global variable to get it like this:

On app/code/Vendor/ModuleName/view/template/frontend/templates/cart/addtocart.phtml

<script type="text/x-magento-init">
    {
        "#product_addtocart_form": {
            "MyAddToCart": ""
        }
    }
</script>
<script>
    var product_sku = '<?php echo $block->getProduct()->getSku(); ?>';
</script>

Then on app/code/Vendor/ModuleName/view/frontend/requirejs-config.js

var config = {
    map: {
        '*': {
            'MyAddToCart': 'Vendor_ModuleName/js/MyAddToCart'
        }
    }
};

Finally on app/code/Vendor/ModuleName/view/frontend/web/js/MyAddToCart.js

define([
    'jquery',
    'jquery/ui',
    'Magento_Catalog/js/catalog-add-to-cart'
], function($){
    "use strict";
    $.widget('Vendor.MyAddToCart', $.mage.catalogAddToCart, {
        submitForm: function(form) {
            var productSku = product_sku;
            //Rest of codes
        }
    });
    return $.Vendor.MyAddToCart;
});

I can get the correct SKU, but how about other product attributes? Seems using global variable method is not so good in this case. Is there any internal methods to get the product attributes inside MyAddToCart without using global variable?

1 Answer 1

2

Your close, you can pass PHP to the JS inside the x-magento-init command:

<script type="text/x-magento-init">
    {
        "#product_addtocart_form": {
            "MyAddToCart": {
                "sku": "<?php echo $block->getProduct()->getSku(); ?>"
            }
        }
    }
</script>

To access it in your JS you need to add the following:

return function (config) {
    var sku = config.sku;
}

I don't have time to test it so let me know if you have any issues.

4
  • Which file should I put the return function into?
    – PY Yick
    Commented Jul 6, 2017 at 10:57
  • @PYYick Your JS file sorry - app/code/Vendor/ModuleName/view/frontend/web/js/MyAddToCart.js
    – Ben Crook
    Commented Jul 6, 2017 at 12:04
  • You can use console.log(config) to see the whole config.
    – Ben Crook
    Commented Jul 6, 2017 at 12:05
  • In my case, I can access the value by this.options.sku . I don't know why but it works even I changed the variable name :)
    – PY Yick
    Commented Jul 7, 2017 at 4:22

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.