Is there a way in Craft Commerce 2 to have a user-input price as a product variant? In my case, I'm offering several pre-set amounts for a donation product (each is a variant), but I also want to offer a "custom amount" option.

Is there a native way to do this? Or a way I can accomplish this with a plugin action?

1 Answer 1


Here's how you could accomplish this.

1) Create a product variant called 'custom amount' with a zero price.

2) Get the ID of that variant

3) When submitting/adding/updating the item to the cart make sure to post an 'amount' line item option. For docs on that see: https://docs.craftcms.com/commerce/v2/adding-to-and-updating-the-cart.html#line-item-options-and-notes

3) Create a plugin/module that attaches this listener:

Event::on(LineItems::class, LineItems::EVENT_POPULATE_LINE_ITEM, function(LineItemEvent $event) {
    $lineItem = $event->lineItem;
    $purchasable = $lineItem->getPurchasable();
    if($purchasable && $purchasable->id = ID_OF_VARIANT_HERE)
        $amount = $lineItem->options['amount'] ?? 0;
            $lineItem->price = $amount;
            $lineItem->salePrice = $amount;

This will set the price to the price of the line item option 'amount' that is submitted.

  • 3
    Wicked, thanks! One note for anyone else coming across this, you'll need to use craft\commerce\services\LineItems; and use craft\commerce\events\LineItemEvent; in your plugin file as well. Commented Aug 28, 2018 at 15:35
  • Is setting a line item's price in an event no longer supported under Commerce 3? This broke for me with the Commerce 3 update. Commented Jun 3, 2020 at 14:29

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.