0

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();
        
     }
}

1 Answer 1

0

I have found solution for this

use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ProductFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\Json as ResultJson;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Data\Form\FormKey;
use Magento\Checkout\Model\Cart;

class Addtocart extends Action
{
    /**
     * @var ProductFactory
     */
    private $productFactory;
    /**
     * @var Cart
     */
    private $cart;
    /**
     * @var FormKey
     */
    private $formKey;
    /**
     * @var JsonFactory
     */
    private $resultJsonFactory;

    /**
     * @param Context $context
     * @param FormKey $formKey
     * @param JsonFactory $resultJsonFactory
     * @param Cart $cart
     * @param ProductFactory $productFactory
     */
    public function __construct(
        Context $context,
        FormKey $formKey,
        JsonFactory $resultJsonFactory,
        Cart $cart,
        ProductFactory $productFactory
    ) {
        parent::__construct($context);
        $this->formKey = $formKey;
        $this->productFactory = $productFactory;
        $this->resultJsonFactory = $resultJsonFactory;
        $this->cart = $cart;
    }

    /**
     *
     * @return ResultJson
     */
    public function execute()
    {
        $data = $this->getRequest()->getParams();
        $resultData = [
            'status' => 'success',
            'status_code' => 1,
            'message' => __('Products Added successfully.')
        ];

        $result = $this->resultJsonFactory->create();
        $qty = 1;

        $product = $this->productFactory->create()->load($productId);
        $productsArray = $this->getBundleOptions($product);
        $params = [
            'product' => $productId,
            'bundle_option' => $productsArray,
            'qty' => $qty
        ];

        try {
            /**
             * Add bundle product in cart
             */
            if ($product->getId()) {
                $this->cart->addProduct($product, $params);
                $this->cart->save();
            }
        } catch (\Exception $e) {
            $resultData = [
                'status' => 'fail',
                'status_code' => 0,
                'message' => __('Unable to add the Product. Exception ' . $e->getMessage())
            ];
            return $result->setData($resultData);
        }
        return $result->setData($resultData);
    }

    /**
     * get all the selection products used in bundle product
     * @param $product
     * @return mixed
     */
    private function getBundleOptions(Product $product)
    {
        $selectionCollection = $product->getTypeInstance()
            ->getSelectionsCollection(
                $product->getTypeInstance()->getOptionsIds($product),
                $product
            );
        $bundleOptions = [];
        foreach ($selectionCollection as $selection) {
            $bundleOptions[$selection->getOptionId()][] = $selection->getSelectionId();
        }
        return $bundleOptions;
    }
}

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.