0

In Magento 2.3 I want to append a shipping method to my collection of methods but it's not working. This is what I'm doing:

  1. I'm selecting the cheapest rate from the collection of rates with $cheapestRate = $this->getResult()->getCheapestRate().
  2. Then, I reset the original collection with $this->getResult()->reset()
  3. I append the cheapest rate to the now clean collection of methods with $method->setCarrier($cheapestRate['carrier']); $method->setCarrierTitle($cheapestRate['carrier_title']); $method->setMethod($cheapestRate['method']); $method->setMethodTitle($cheapestRate['method_title']); $method->setCost($cheapestRate['cost']); $method->setPrice($cheapestRate['price']); $result->append($method); $this->getResult()->append($result);

  4. I'm displaying the cheapest rate so far. Now, I want to add a custom method with a cost of $0.00. This is what I do: private function addCustomShippingToMethods($method, $result) { $method->setCarrier('custom_shipping'); $method->setCarrierTitle('custom_shipping'); $method->setMethod('custom_shipping'); $method->setMethodTitle('custom_shipping'); $method->setPrice(0); $method->setCost(0); $result->append($method); return $this; }

  5. So, to insert the custom method in step 4, I call addCustomShippingToMethods right after the last line in step 3 like this $this->addCustomShippingToMethods($method, $result);

The problem is that I only see the custom method in the checkout page but not the cheapest one. If I remove the call to add the custom method then I only see the cheapest one.

In a few words, all the shipping options I want to see in the checkout page are the cheapest rate and the custom shipping at $0.00.

What am I doing wrong?

Thanks for any advice.

  • I made it work. I'll be back with a solution soon. – luenib Jan 14 at 17:55
0

So, in order to make it work I had to change step 4. It goes like this:

private function addCustomShippingToMethods() {
    $method = $this->_rateMethodFactory->create();
    $result = $this->_rateResultFactory->create();

    $method->setCarrier('custom_shipping');
    $method->setCarrierTitle('custom_shipping');
    $method->setMethod('custom_shipping');
    $method->setMethodTitle('custom_shipping');
    $method->setPrice(0);
    $method->setCost(0);
    $result->append($method);

    return $result;
}

Then I change step 5 with this:

$this->addCustomShippingToMethods();

Silly me. I thought I didn't need to create a $method and a $result for the custom shipping method since they were already there. I also had to return $result, not $this.

I hope this helps somebody.

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.