cancel
Showing results for 
Search instead for 
Did you mean: 

How to get shipping rates with Address and carrier

How to get shipping rates with Address and carrier

Hi,

  I have a block of custom module like this

use Magento\Shipping\Model\Shipping;
class Abc extends \Magento\Framework\View\Element\Template {     protected $_scopeConfig;
    protected $_shipModel;
protected $_checkoutSession;
public function __construct(\Magento\Framework\View\Element\Template\Context $context,\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,array $data = [], \Magento\Checkout\Model\Session $checkoutSession,
\Magento\Shipping\Model\Shipping $shippingModel ) { parent::__construct($context, $data); $this->_scopeConfig = $scopeConfig; $this->_checkoutSession = $checkoutSession;
        $this->_shipModel = $shippingModel; } function getCheckOutSession() { return $this->_checkoutSession; }

function shippingPrice () {
 
    $session = $this->getCheckOutSession();
    $address = $session->getQuote()->getShippingAddress();
    $address->setCountryId("US")
            ->setCity("New York")
            ->setPostcode("11209")
            ->setRegionId("")
            ->setRegion("")
            ->setCollectShippingRates(true)->collectShippingRates();

    $shippingCarrier = 'flatrate';
    $carriers[$shippingCarrier] = '';
    $result = $this->_shipModel->collectRatesByAddress($address, array_keys($carriers))->getResult();
    foreach ($result->getAllRates() as $rate) {
    ...
    }
    ...
} }

it is my template file

$session = $this->getCheckOutSession();
echo $this->shippingPrice();

But this line of code in my template

$this->shippingPrice();

giving me nothing and the cart page renders as normal.

Thanks in advance.