Problem/Motivation

When manually creating or editing a draft Commerce order in the admin UI and adding a shipment before any order items exist, CurrencyResolverShippingTrait::calculateRates() throws a fatal error:

  Error: Call to a member function getCurrencyCode() on null in
  Drupal\commerce_currency_resolver_shipping\Plugin\Commerce\ShippingMethod\FlatRateCurrency->calculateRates()
  (line 45 of modules/shipping/src/Plugin/Commerce/ShippingMethod/CurrencyResolverShippingTrait.php)

This happens because $order->getTotalPrice() returns NULL when the order has no items, and the code calls ->getCurrencyCode() on it without a null check.

The same issue exists in selectRate() at line 68.

Steps to reproduce

1. Go to /admin/commerce/orders/add
2. Select a customer and store
3. Before adding any order items, click "Add shipment"
4. Enter a shipping address and submit
5. Fatal error on shipping rate calculation

Proposed resolution

Add null checks for getTotalPrice() in both calculateRates() and selectRate(), falling back to the parent implementation when the order has no total price yet.

public function calculateRates(ShipmentInterface $shipment): array {
    if ($order = $shipment->getOrder()) {
      $totalPrice = $order->getTotalPrice();
      if (!$totalPrice) {
        return parent::calculateRates($shipment);
      }
      $amount = $this->getRatesAmount($totalPrice->getCurrencyCode());
      // ... rest unchanged
public function selectRate(ShipmentInterface $shipment, ShippingRate $rate) {
    parent::selectRate($shipment, $rate);
    if ($order = $shipment->getOrder()) {
      $totalPrice = $order->getTotalPrice();
      if (!$totalPrice) {
        return;
      }
      $order_currency = $totalPrice->getCurrencyCode();
      // ... rest unchanged

This is consistent with how Commerce core addressed the same class of NULL price issues in #2998065: Ensure all calls to price getters handle NULL returns.

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

introfini created an issue. See original summary.

valic made their first commit to this issue’s fork.

valic’s picture

seems tests are failing for shipping now, did fix them in previous ticket. Investigating

valic’s picture

Added tests, updated, can't replicate anymore the issue

valic’s picture

Status: Active » Fixed

Now that this issue is closed, review the contribution record.

As a contributor, attribute any organization that helped you, or if you volunteered your own time.

Maintainers, credit people who helped resolve this issue.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.