2

I am currently migrating a store from Magento 1.7 to Magento 2.2

On many of our product pages there is a button to order a free sample which is achieved by adding a product 'free sample' with options that detail the product in question. The adding to cart is done using a GET request like the following:

    <script type="text/javascript">
function addsample(){
window.location.href='<?php //echo $home_url ?>/checkout/cart/add?product=113&qty=1&options[410]=<?php echo $productname ?>&options[450]=<?php echo $productimg ?>&options[563]=<?php echo $prodid ?>&options[451]=<?php echo $producturl ?>';
}
</script>

<div class="clearer"></div>
<div style="margin:10px 0 20px 0"><button type="button" id="cartbutton" title="sample" class="btn btn-md btn-default" style="height:38px;" onclick="addsample()"><span class="glyphicon glyphicon-envelope"></span>&nbsp;Order Free Sample</button></div>

Can the same be achieved in Magento 2.2?

I have done some research and found that I can get an addtocart url by making a function like the following in my block:

public function getLoadProductAddUrl($id)
{
    $product = $this->_objectManager->create('Magento\Catalog\Model\Product')->load($id);
    return $this->_objectManager->get('Magento\Checkout\Helper\Cart')->getAddUrl($product);
}

And that gives me the following:

https://tmp.domain/checkout/cart/add/uenc/aHR0cHM6Ly90bXAuZmxvb3JzYXZlL25vY2UtcnViaW8td2FsbnV0LXByZW1pdW0tbGFtaW5hdGUtZmxvb3JpbmctMTJtbS5odG1s/product/113/

This will take me to the shopping cart but nothing is added. I am also aware that there is such a thing as FormKey and I am able to get that with a function in my block like:

public function getFormKey(){
    $formKey = $this->_objectManager->get('Magento\Framework\Data\Form\FormKey');
    return $formKey->getFormKey();
}

But then I am not submitting a form with POST but trying to use GET.

Should the FormKey be added to the URL? Can I add options to the query string in the same way as it is done in our Magento 1.7 version?

Is it simply not possible to do like this with a GET and query string as the latest best practice security and so on dictates that a form should be used?

  • Anyone have even a vague idea or direction you could point in please? @PrincePatel – Matt Nov 20 '17 at 13:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.