How to setup a Drupal Commerce Order total Range condition
Auteur(s) de l'article
The other day, I faced a serious problem. One of our clients wanted a new shipping methods that must be applied on Ranged Order Total Price condition.
AKA a shipping method that must apply only when the order total falls within a range. E.g. $100 => order total <= $200.
After digging the Drupal Commerce Issue Queue, I found out there is no out-of-the-box solution/patch (for now) to apply an Order Total Price within a range Condition. So let's code it !
The Plugin Condition
For the most curious ones, here is a unit test Class that you may be interested to add on your project to ensure plugin stability: https://gist.github.com/WengerK/edbe17bb52067c5be86f34d1d1d2bd4e#file-ordertotalpricerangetest-php.
That's pretty much all the hocus-pocus that you need to have custom Commerce Total Price Order Condition fitting within a range.
Going Further
The code upper here is simplified.
Still, you may want to change the code in order to exclude adjustments or change the in between operators used.
Total price includes adjustments
You may want to remove the adjustments (taxes, shipping, etc ...) in order to trigger the condition.
Then update the
OrderTotalPriceRange::evalute
method.// (...)
if (!$total_price) {
return FALSE;
}
// Subtract tax & shipping adjustments.
$adjustments = $order->collectAdjustments(array_filter(['tax', 'shipping']));
foreach ($adjustments as $adjustment) {
$total_price = $total_price->subtract($adjustment->getAmount());
}
// (...)
Configurable between operators
The given plugin use a hardcoded “Between” condition including the input values (
>= && <=
).You can still change this condition by updating the
return
condition of OrderTotalPriceRange::evalute
.return $total_price->greaterThan($condition_price_from)
&& $total_price->lessThan($condition_price_to);
Credits
Many thanks to Quentin Fahrner for sharing with me an inital Plugin solution.
Sources
For the most curious of you, here are some sources of additional information that inspired the creation of this article.
Quentin Fahrner (11 May, 2022). Order total range condition.
See on https://www.drupal.org/project/commerce/issues/2938731
See on https://www.drupal.org/project/commerce/issues/2938731
Retrieve all the code on Gist: https://gist.github.com/WengerK/edbe17bb52067c5be86f34d1d1d2bd4e