0

Background

I've built a custom shipping method. It follows almost an identical pattern to the magento shipping method classes. It works as expected. Then I added a plugin to check if a coupon code was entered the field would appear. This works as well.

The Issue

I want to attach the coupon name to the shipping method title. So instead of saying "Event Pickup FREE" it says "EVENT LOCATION - Event Pickup - FREE". Making an afterCollectRates function I would assume I would need to alter the $result variable.

I can't seem to figure out how to:

  1. Properly alter $result to override the data.

  2. Debug or log $result to see the structure of the object. In hopes to alter it.

Shipping Method Function

  public function collectRates(RateRequest $request)
  {
    if (!$this->getConfigFlag('active')) {
        return false;
    }

    /** @var \Magento\Shipping\Model\Rate\Result $result */
    $result = $this->_rateResultFactory->create();

    /** @var \Magento\Quote\Model\Quote\Address\RateResult\Method $method */
    $method = $this->_rateMethodFactory->create();

    $method->setCarrier($this->_code);
    $method->setCarrierTitle($this->getConfigData('title'));

    $method->setMethod($this->_code);
    $method->setMethodTitle($this->getConfigData('name'));  //<--This is what the plugin should change

    $method->setPrice('0.00');
    $method->setCost('0.00');

    $result->append($method);

    return $result;
  }

Plugin for Shipping Method

public function afterCollectRates(\Base\Model\Carrier\EventPickup $subject, $result)
{

    if (!$this->checkCouponCode()) {
            return false;
    }

    $couponCode = $this->_coupon->getCouponCode()


    $this->_logger->debug($couponCode); //<--This works and shows up on log

    return $result;
}

I've attempted to use the logger, debug, var_dump, echo, print_r, var_export and any other combinations. All seem to be no use. The result is usually the same, the magento loader spins forever and nothing regarding $result comes to the log. Thanks for the help!

1 Answer 1

1

You can't log objects. But you can log data of it. For debug logging I usually use Zend logger with custom writer:

        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/test.log');
    $logger = new \Zend\Log\Logger();
    $logger->addWriter($writer);
    $logger->info($result->getAllRates()[0]->getData());

And as you can already guess - you can change your method like this: $result->getAllRates()[0]->setData('data_name', 'new_data_value')

Hope it will help.

2
  • This looks promising - I'll take a look and report back. thanks! Commented Mar 4, 2018 at 23:14
  • 1
    @SpencerRohan nice to hear. Enjoy coding! Commented Mar 5, 2018 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.