Magento 2.1.4 – Add Product to Cart Programmatically with Custom Price

custom-pricesmagento-2.1.4

I want to add product with custom price in cart/checkout only but the original price of product should not get any affect.

So far I've achieved this.I'm adding product programmatically based on some condition. Not using any observer or something I'm just passing product id to my custom controller and adding that product into cart.

public function execute(){
    ....
    $productObj->setData('_edit_mode', true);
    $productObj->setPrice(8000);
    $productObj->setFinalPrice(8000);
    $productObj->save();
    $this->cart->addProduct($productObj, $product);
    ....
    $this->cart->save();
}

Using above function only product original price get changed but not in cart so what can be done to do so?

Best Answer

I've resolved by following

public function execute(){
    ....
    $finalPrice =  $totalQty * $product->getKrat() * $price;
    $item->setCustomPrice($product->getKrat() * $price);
    $item->setOriginalCustomPrice($finalPrice);
    $item->getProduct()->setIsSuperMode(true);
    $item->setQty(0);
    $item->save();
}
Related Topic