7

Rather than a static price for each product, I need the price to be dynamic based on two other fields of that product. Here's an example of what I need to accomplish:

Product

Field 1: Wholesale Cost (int)
Field 2: Increase Factor (int)

Price: (Wholesale Cost * Increase Factor) + Wholesale Cost

Digging around, I am finding absolutely nothing in regards to making the price of products dynamic. Is this possible at all with Craft Commerce, and if so how would I go about this?

  • I'm working on a same kind of dynamic priced product, thanks for your tip. I'm wondering, how would you save the modified price? Trying 'craft()->commerce_orders->saveOrder($order);' doesn't do anything yet, but i'll try some other ways. Thanks, Bob – Bob Donderwinkel May 30 '16 at 20:37
8

[** Updated Dec 2016]

I think at this stage the best approach will be plugin based.

Create a business logic plugin if you haven't already.

Two good ways of doing that are : Business Logic Plugin or via https://pluginfactory.io

If you listen to: https://craftcommerce.com/docs/events-reference#commerce_lineitems.onpopulatelineitem

...then you can do (basically any) logic on the price as it is created as a lineItem in the cart (i.e. added to the cart).

Here's some sketch code to get you started:

craft()->on('commerce_lineItems.onPopulateLineItem', function($event){

  $purchasable= $event->params['purchasable'];
  $lineItem = $event->params['lineItem'];

  if(isset($lineItem->options['giftWrapped']) && $lineItem->options['giftWrapped'] == 'yes')){
      $lineItem->price = $lineItem->price + 1;
  }

});
  • 1
    Off-topic but I dig that term, "sketch code". (I've used "roughs" before but in some cases, sketch code is a better description.) – RitterKnight May 27 '16 at 13:57
  • Think this needs to be onBeforeSaveLineItem ? Otherwise it's triggered after the line item has been saved? – user155 Jun 2 '16 at 21:43
  • Right you are! Will update – Jeremy Daalder Jun 2 '16 at 21:44
  • A further update - Commerce (v 1.1.1211+) has just got a new event - craftcommerce.com/docs/… - which now appears to to the the recommended point to address the pricing of the purchasable. – Jeremy Daalder Jun 7 '16 at 23:41
  • What about the 'commerce_products.onBeforeSaveProduct' event? It seems like it would be better to do this price change whenever creating or updating a product, that way I can display the proper price on the front end. I'm having difficulty figuring out how to get the price using this event, and furthermore how it would save the update price. Is there an example on manipulating data like this via init() somewhere? – taylor Jun 15 '16 at 18:38

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.