Score:0

Get list of applicable shipping methods

ni flag

I would like to get the list of applicable shipping methods for the current cart but dependent on the selected shipping profile. I'm programming a custom controller that should returns the list of available shipping methods and rates but, obviously, given a cart and a customer's shipping profile.
Has commerce shipping module any service or class that could I use to get this information? Perhaps, is there any other way to get it?

I've been reading source code from:
Commerce_Shipping\src\Plugin\Commerce\CheckoutPane\ShippingInformation.php
That is the CheckoutPane plugin that renders shipment options in checkout page. buildPaneForm method renders this form, and those lines of code should give me the list of shipping methods:

 public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    ...
    $shipments = $this->order->get('shipments')->referencedEntities();
    ...
    foreach ($shipments as $index => $shipment) {
    ... // all shipments
    }

But I have tried it in my custom controller and It always returns empty array. I think there should be a prior process that populate this list, but I can't find it. I have tried appling a state transition but It doesn't work.

Score:0
ni flag

After some in-depth research on commerce modules, I have found a way to get them. This is an excerpt of the source code with the main instructions (controller class that returns JSON):

public function getShippingMethods(Request $request, $id) {
          
    $commerce_order = Order::load($id);       
    // ... some checks to ensure it is a commerce order

    $shipments = $commerce_order->get('shipments')->referencedEntities();
    
    $options = [];
    foreach ($shipments as $shipment) {     
      assert($shipment instanceof ShipmentInterface);      
      $rates = $this->shipmentManager->calculateRates($shipment);
      foreach($rates as $rate) {
        $options[] = [ "id" => $rate->getShippingMethodId(), 
                       "method" => $rate->getService()->getLabel(), 
                       "import" => $rate->getAmount()->getNumber(),
                       "description" => $rate->getDescription()];              
      }
    }
            
    // Return JSON with all shipping methods
    return new JsonResponse( $options );
  }

Hope It could help someone.

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.