0

i'm using magento v2.4.1. I tried to add the product to the cart programmatically using salesrule_validator_process observer, this is to add a product if a cart rule being applied to the cart:

$quote = $observer->getEvent()->getQuote();
$productId = 15;
$qty = 1;
$product = $this->productRepository->getById($productId, false, $storeId);
$addResult = $quote->addProduct($product,$qty);
$newQuoteItem = $addResult;
$newQuoteItem->setCustomPrice(0);
$newQuoteItem->setOriginalCustomPrice(0);
$newQuoteItem->setBaseTaxCalculationPrice(0);
$newQuoteItem->setTaxCalculationPrice(0);
$newQuoteItem->setNoDiscount(true);
$newQuoteItem->getProduct()->setIsSuperMode(true);
$newQuoteItem->calcRowTotal();

The problem is this observer only fires at quote collect totals, so sometimes is not firing at the checkout cart page or checkout page, is there a way to include the collect totals at the checkout page or checkout cart page when the customer first visit the page ? is it safe to do this ?

1 Answer 1

0

This is not the safe way to do this:

you must add product using checkout_submit_before event.

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_submit_before">
        <observer name="quoteSubmitBefore" instance="namespace\module\Observer\QuoteSubmitBefore" />
    </event>
</config>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.