cancel
Showing results for 
Search instead for 
Did you mean: 

How to override the "getAddToCartUrl()" function?

   Did you know you can see the translated content as per your choice?

Translation is in progress. Please check again after few minutes.

How to override the "getAddToCartUrl()" function?

I'm attempting to override the "getAddToCartUrl" function, in "AbstractProduct.php", found at \vendor\magento\module-catalog\Block\Product.

Essentially, I'm looking to modify it, so that it simply ignores the "hasRequiredOptions()" check and just returns the url, regardless of the product type. Here's the code for "getAddToCartUrl" - 

if ($product->getTypeInstance()->hasRequiredOptions($product)) {
     if (!isset($additional['_escape'])) {
          $additional['_escape'] = true;
     }
     if (!isset($additional['_query'])) {
          $additional['_query'] = [];
     }
     $additional['_query']['options'] = 'cart';

     return $this->getProductUrl($product, $additional);
}
return $this->_cartHelper->getAddUrl($product, $additional);

 

 

I've attempted to create a module that simply overrides this function, but it isn't being called (I believe the module is enabled properly, as I can see it displayed as "enabled" in the backend).

I'm hoping someone can point me in the correct direction, with some helpful tips/reading material.

 

Thanks in advance!

2 REPLIES 2

Re: How to override the "getAddToCartUrl()" function?

Re: How to override the "getAddToCartUrl()" function?

Thanks for the reply, zhdiroda.

That method didn't work, but here's what I tried (in case I've done something incorrectly).

- set the registration.php file.

- set the module.xml file.

- inserted this line in the \app\code\{namespace}\{module}\etc\di.xml file:

<preference for="Magento\Catalog\Block\Product" type="{namespace}\{module}\Block\ExtendProduct" />

 

- Created the file, "AbstractProduct.php" at \app\code\{namespace}\{module}\Block, and added this code:

namespace <namespace>\<module>\Block;
class AbstractProduct extends \Magento\Catalog\Block\Product
{
    public function getAddToCartUrl($product, $additional = [])
    {
        return $this->_cartHelper->getAddUrl($product, $additional);
    }
}

- I deleted the \pub\static folder and the \var\cache, \var\composer_home, \var\generation, \var\page_cache and \var\view_preprocessed folders.

- ran the command, "setup:static-content:deploy" and refreshed the page.