0

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.

1 Answer 1

0

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.

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.