Score:2

How do I get rate and configuration values?

ar flag

I'm stumped. How do you get values off of the shipment method config? For example I have a the Flat Rate shipping method "Express". I want to get the raw config form values stored on that shipping method. Such as rate, or a custom field I've provided.

I've plugged into the shipping methods to add a custom form field. But now need to retrieve it later on. The values aren't on the shipment entity.

    $shippingMethodId = $commerceOrder->shipments->entity->shipping_method->entity->shipping_method_id->value;
    $shipping_method_storage = \Drupal::entityTypeManager()->getStorage('commerce_shipping_method');
    $shipping_method = $shipping_method_storage->load($shippingMethodId);
    //$shipping_method->rate->value
    //$shipping_method->honeys_place_shipping_code->value

I've tried appending the values to the ShippingRate returned from calculateRates()

public function calculateRates(ShipmentInterface $shipment) {
    $rates = [];
    $rates[] = new ShippingRate([
      'shipping_method_id' => $this->parentEntity->id(),
      'service' => $this->services['default'],
      'amount' => Price::fromArray($this->configuration['rate_amount']),
      'description' => $this->configuration['rate_description'],
      'honeys_place_shipping_code' => $this->configuration['honeys_place_shipping_code'] // < -----
    ]);

    return $rates;
  }

This fires but does not make it into the shipment entity on the order later. I know I can retrieve the rate by accessing 'amount' off of the shipment entity. But I also need to retrieve custom values.

Is there a way to retrieve these values from config or get them onto the shipment entity object?

enter image description here

Score:2
cn flag
$shippingMethodId = $commerceOrder->shipments->entity->shipping_method->entity->shipping_method_id->value;
$shipping_method_storage = \Drupal::entityTypeManager()->getStorage('commerce_shipping_method');
$shipping_method = $shipping_method_storage->load($shippingMethodId);

$rate = $shipping_method->plugin->getValue()[0]['target_plugin_configuration']['rate_amount'];

You'll have to dig deeper on the plugin field from the shipping_method entity.

$shipping_method->plugin->getValue()[0];
// This will return the following array below

enter image description here

Matt Campbell avatar
ar flag
Beautiful thanks. I didn't think to look there.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.