Skip to content

Instantly share code, notes, and snippets.

@TommyKolkman
Created May 30, 2016 13:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TommyKolkman/fc0b7bf392769bc28cb41828b8245bd3 to your computer and use it in GitHub Desktop.
Save TommyKolkman/fc0b7bf392769bc28cb41828b8245bd3 to your computer and use it in GitHub Desktop.
Add product to cart in Magento 2
public function __construct(
\<Vendor>\<ModuleName>\Helper\HelperName $helperName,
array $data = []
) {
$this->_helperName = $helperName;
}
namespace <Vendor>\<ModuleName>\Helper;
class HelperName extends \Magento\Framework\App\Helper\AbstractHelper
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\Data\Form\FormKey $formKey,
array $data = []
) {
$this->_storeManager = $storeManager;
$this->_formKey = $formKey;
parent::__construct( $context, $data );
}
public function getAddToCartUrl( $productId ){
$resultPage = $this->_resultPageFactory->create();
$params = array(
'form_key' => $this->_formKey->getFormKey(),
'product' => $productId, // Product Id
'qty' => 1 // Quantity of product
);
$addToCartUrl = $this->getCurrentStore()->getBaseUrl() . 'checkout/cart/add/?' . http_build_query( $params );
return $addToCartUrl;
}
public function getCurrentStore(){
return $this->_storeManager->getStore();
}
}
$addToCartUrl = $this->_helperName->getAddToCartUrl( $product->getId() );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment