Created
May 30, 2016 13:23
-
-
Save TommyKolkman/fc0b7bf392769bc28cb41828b8245bd3 to your computer and use it in GitHub Desktop.
Add product to cart in Magento 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public function __construct( | |
\<Vendor>\<ModuleName>\Helper\HelperName $helperName, | |
array $data = [] | |
) { | |
$this->_helperName = $helperName; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$addToCartUrl = $this->_helperName->getAddToCartUrl( $product->getId() ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment