1

We're building a webshop with Craft and Craft Commerce. The products will have dynamic pricing based on the weight and material.

Is it possible to extend Craft Commerce products to add these fields and update the price based on the inputted values? Basically what we need is a small price calculator in the product form.

1 Answer 1

2

You can add weight and material as custom fields to the product type. For the weight, you can also use the built-in field.

To dynamically calculate the price, you could inject a bit of JavaScript that updates the price when either the material or weight fields are changed. However, this will not apply when products are programmatically created or updated.

As an alternative, or in addition to this, you can use event hooks. For example, you can hook into the Product::EVENT_BEFORE_SAVE event to update the price based on your custom calculation right before a product is saved. This will work regardless of how a product is created or edited.

In either case, you may want to add instructions to your price field to explain that the price is updated dynamically, so authors won't try to change it manually. You can also inject JavaScript to set the price input to disabled to prevent this entirely.

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.