0

So right now I'm creating an add to cart button on a custom PHTML file to create a special landing page using the following code:

<?php

$cartHelper = $this->helper('Magento\Checkout\Helper\Cart');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Catalog\Model\Product')->load(590);

?>
    <form data-role="tocart-form" action="<?php echo $cartHelper->getAddUrl($product); ?>" method="post"> 
        <?php echo $block->getBlockHtml('formkey')?>
        <button type="submit" title="Add to Cart" class="btn action tocart primary">
            <span>ADD TO CART</span>
        </button>
    </form>

This seems to work fine. I realize that using Object Manager is not going to be ideal, however I've tried everything else under the sun and this is the only thing that works. Most other solutions don't even explain how you set the specific Product ID that's getting added.

Even though this works fine we are now working on a page that has multiple products displayed on the same page. The problem here is that all the Form links go to the same product URL. So whatever is set first all the links end up adding the same product to the cart even though I redefine those variables. The page is made up of multiple PHTML files for different blocks to make it easier to program. The strange thing is that about half way down the page the links change to reference a URL in one file, but then they are all that new Product ID for the rest of the page.

I've even tried using:

$product5 = $objectManager->get('Magento\Catalog\Model\Product')->load(590);
$product6 = $objectManager->get('Magento\Catalog\Model\Product')->load(591);
$product7 = $objectManager->get('Magento\Catalog\Model\Product')->load(349);

And it won't matter even with Unique variable names they come back all as product ID 590

0

I discovered this is actually working fine. The reason it wasn't working is because I was building and testing this on a Staging Environment for some Holiday Products. The Holiday products existed on Production but not on Staging. When set to products that exist it works fine changing the Product as it should. So the key here is make sure the product ID exists.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.