1

I want to add range field that will change price based on its value. How can I send updated price to the cart? Is there something easy like:

{% set product = craft.products.one() %}
{% set variant = product.defaultVariant %}

<form method="POST">
    <input type="hidden" name="action" value="commerce/cart/update-cart">
    {{ redirectInput('shop/cart') }}
    {{ csrfInput() }}
    <input type="hidden" name="price" value="HERE NEW PRICE">
    <input type="hidden" name="purchasableId" value="{{ variant.id }}">
    <input type="submit" value="Add to cart">
</form>
3

It's not possible to send the price to the cart in this way.

You will need to send that price as a custom option on the item and then use a custom module or plugin to update the line item's price.

You can just alter the line item price directly if desired but it may be more appropriate to create an adjuster to do it.

So your add to cart form might look like...

<form method="POST">
    <input type="hidden" name="action" value="commerce/cart/update-cart">
    {{ redirectInput('shop/cart') }}
    {{ csrfInput() }}
    <input type="hidden" name="options[customPrice]" value="HERE NEW PRICE">
    <input type="hidden" name="purchasableId" value="{{ variant.id }}">
    <input type="submit" value="Add to cart">
</form>

Then your custom module would listen for a Commerce event, probably populateLineItem (see events here https://docs.craftcms.com/commerce/v2/events.html#order-related-events) and update the item's price.

use craft\commerce\events\LineItemEvent;
use craft\commerce\services\LineItems;
use yii\base\Event;

Event::on(LineItems::class, LineItems::EVENT_POPULATE_LINE_ITEM, function(LineItemEvent $e) {
   // update the line item's price with the customPrice option from this line item
   // save the line item
});
  • probably: public function handlePopulateLineItem(LineItemEvent $event) { $options = $event->lineItem->getOptions(); if (isset($options['customPrice'])) { $event->lineItem->price = $options['customPrice']; } } – Nikolay Bronskiy Aug 25 at 16:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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