I created a new product programmatically and added it to the cart, but the subtotal value which is showing in the cart is 0
.
use \Magento\Catalog\Model\ProductFactory;
use \Magento\Catalog\Api\ProductRepositoryInterface;
...
/**
* @var \Magento\Catalog\Model\ProductFactory
*/
protected $productFactory;
/**
* @var \Magento\Catalog\Api\ProductRepositoryInterface
*/
protected $productRepository;
...
public function __construct(
ProductFactory $productFactory,
ProductRepositoryInterface $productRepository,
) {
$this->productFactory = $productFactory;
$this->productRepository = $productRepository;
}
...
$product = $this->productFactory->create();
$product->setName($data["name"]);
$product->setSku($data["sku"]);
$product->setPrice($data["difference"]);
$product->setTypeId("virtual");
$product->setWeight(0);
$product->setTaxClassId($this->taxClassId);
$product->setVisibility(1);
try {
$product = $this->productRepository->save($product);
} catch (CouldNotSaveException $e) {
$this->logger->info("CouldNotSaveException : ". $e->getMessage());
} catch (InputException $e) {
$this->logger->info("InputException: " . $e->getMessage());
} catch (StateException $e) {
$this->logger->info("StateException: ". $e->getMessage());
}
...
$this->quote->addProduct($product);
$this->quote->save();