Like given in this blog for magento1 i want to add custom options in list page for magento 2. is there any module available for same or can someone guide me to achieve this?
1 Answer
I've implement code for it. Please create block class Don't use Object Manager directly on template. I've used this for demo.
<?php
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customOptions = $_objectManager->get('Magento\Catalog\Model\Product\Option')->getProductOptionCollection($_product);
$optStr = "";
foreach($customOptions as $optionKey => $optionVal):
$optStr .= "<div class='custom-options'><label>".$optionVal->getTitle()." </label>";
$optStr .= "<select name='options[".$optionVal->getId()."]'>";
foreach($optionVal->getValues() as $valuesKey => $valuesVal) {
$optStr .= "<option value='".$valuesVal->getId()."'>".$valuesVal->getTitle()."</option>";
}
$optStr .= "</select></div>";
endforeach;
echo($optStr );
?>
-
NOt Working ... When i click on add to cart page redirect on Detail Page Commented May 3, 2018 at 14:05
-
The answer is correct, but you will be redirected to the product detail page because Magento assumes the user needs to fill in the custom options there, so it creates the wrong form action URL. To fix this, declare a helper:
$_cart_helper = $this->helper('Magento\Checkout\Helper\Cart');
Then, use this as your form action URL:$_cart_helper->getAddUrl($_product)
– ArneCommented Jun 9, 2019 at 19:09 -