I am working on cms page custom product layout for that I have written custom controller. but it show error
{"0":"Please select all required options.","1":"#1 Magento\Checkout\Model\Cart\Interceptor->addProduct() called at [app/code/Vendor/SmallBusiness/Controller/Index/AddCart.php:73]\n#2 Vendor\SmallBusiness\Controller\Index\AddCart->execute() called at [generated/code/Vendor/SmallBusiness/Controller/Index/AddCart/Interceptor.php:24]\n#3
Below is my controller
namespace Vendor\SmallBusiness\Controller\Index;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Data\Form\FormKey;
use Magento\Checkout\Model\Cart;
use Magento\Catalog\Model\ProductRepository;
class AddCart extends Action
{
protected $formKey;
protected $cart;
protected $productRepository;
public function __construct(
Context $context,
FormKey $formKey,
Cart $cart,
ProductRepository $productRepository) {
$this->formKey = $formKey;
$this->cart = $cart;
$this->_productRepository = $productRepository;
parent::__construct($context);
}
public function execute()
{
$id = $this->getRequest()->getParam('product_id');
$quote = $this->cart;
$_product = $this->_productRepository->getById($id);
$selectionCollection = $_product->getTypeInstance(true)
->getSelectionsCollection(
$_product->getTypeInstance(true)->getOptionsIds($_product),$_product);
// create bundle option
$cont = 0;
$selectionArray = [];
$selectionqtyArray = [];
$selectionpriceArray = [];
foreach($selectionCollection as $proselection){
$selectionArray[$cont] = $proselection->getSelectionId();
$selectionqtyArray[$cont] = $proselection->getSelectionQty();
$selectionpriceArray[$cont] = $proselection->getPrice();
$cont++;
}
// get options ids
$optionsCollection = $_product->getTypeInstance(true)->getOptionsCollection($_product);
foreach ($optionsCollection as $options) {
$id_option = $options->getId();
}
// generate bundle_option array
$bundle_option = [$id_option => $selectionArray];
$bundle_qty = [$id_option => $selectionqtyArray];
$bundle_price = [$id_option => $selectionpriceArray];
$params = [
'product' => $_product->getId(),
'bundle_option' => $bundle_option,
'bundle_option_qty' => $bundle_qty,
'bundle_option_price' => $bundle_price,
'qty' => 1,
'original_qty' => 1
];
$quote->addProduct($_product, $params);
$quote->save();
}
}