简体   繁体   中英

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

Why is the documentation of Magento this bad? It's pretty difficult to build a plugin for it. Anyways I try to add a product with custom price and options. In WooCommerce it's extremely easy to do that.

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.

Thanks.

You can use OOTB Magento API endpoint for adding product to cart.

Here is the explanation for payload data for different product types, and it can be helpful. https://devdocs.magento.com/guides/v2.3/rest/tutorials/orders/order-add-items.html

But Magento does not allow you to add product to cart with custom price via payload data. You will have to add observer and implement the logic around pricing. More details here. https://www.mageplaza.com/devdocs/add-product-to-cart-with-custom-price-magento-2.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM