2

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?

4

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;
        if($amount)
        {
            $lineItem->price = $amount;
        }
    }
});

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

  • 2
    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. – Derek Hogue Aug 28 '18 at 15:35

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.