cancel
Showing results for 
Search instead for 
Did you mean: 

Magento 2.3.5: Add product to cart with custom options and price

Magento 2.3.5: Add product to cart with custom options and price

Hello guys,

 

I try to add a product with custom price and options. In WooCommerce it's extremely easy to add the product to cart and to add custom options as well as a custom price to it. The option were not set before adding the product to cart and can be anything. I would like to accomplish something similar in Magento.

 

My code looks like this:

protected $_cart;
protected $_productFactory;

 

Constructor:

public function __construct(
\Magento\Checkout\Model\Cart $cart,
\Magento\Catalog\Model\ProductFactory $productFactory
) {
$this->_cart = $cart;
$this->_productFactory = $productFactory; }

 

Execute:

$product = $this->_productFactory->create()->load($product_id);     

$params = array(
    'qty' => 1,
    'price' => 100,
    'product' => $product_id,
    'options' => array(
        "test" => array(
            'label' => 'Print Style',
            'value' => 'Test'
        )
    )
);

$this->_cart->addProduct($product, $params);
$this->_cart->save();

 

The controller is called via an ajax post request. The product will be added to the cart and the amount of products equals the quantity I stated in my array.

There are several problems though:

  1. The product is only visible in the cart after adding a different product to it via the regular add to cart button.

  2. The price is not adjusted. The normal price is used.

  3. The custom option isn't visible. The custom option should be visible in the cart, at the checkout and in the order details.

 

How am I able to accomplish that? I appreciate your help.

 

Thank you!