3

I want to display a custom message in shipping method section. The message is displayed based on the country and cart weight.

I have created a custom block in shipping method section. Now it is displayed only for logged in customers.

I want to reload the message section when the country changed. How can I do it? Here is my code

Namespace/Module/view/frontend/web/template/checkout/shipping/shipmessage-block.html

<!-- ko if: isMessage() -->
<div class="checkout-block" id="block-custom">
    <p data-bind="text: getMessage()"></p>
</div>
<!-- /ko -->

Namespace/Module/Model/ShipmessageConfigProvider.php

 public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Checkout\Model\Cart $cart,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfiguration,
        \Magento\Framework\Stdlib\DateTime\TimezoneInterface $date,
        \Magento\Framework\ObjectManagerInterface $objectmanager,
        \Magento\Quote\Model\Quote $quote,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Framework\Serialize\Serializer\Json $serialize
    ) {
        $this->scopeConfiguration = $scopeConfiguration;
        $this->cart = $cart;
        $this->_objectManager = $objectmanager;
        $this->quote = $quote;
        $this->date = $date;
        $this->_checkoutSession = $checkoutSession;
        $this->serialize = $serialize;
    }
    /**
     * @return array() $showHide
     */
    public function getConfig()
    {

        $shipMessage = [];
        $shipMessage['ship_message'] = $this->getShipMessage();
        return $shipMessage;
    }

    public function getShipMessage()
    {

        $quote = $this->_checkoutSession->getQuote();
        $countryId = $quote->getShippingAddress()->getCountryId();
        $items = $quote->getAllItems();
        $cartWeight = 0;
        foreach($items as $item) {
            $cartWeight += ($item->getWeight() * $item->getQty()) ;
        }      
        $message ="Cart Weight is " .$cartWeight;
        return $message;
    }

Namespace/Module/view/frontend/web/js/view/checkout/shipping/shipmessage-block.js

define([
    'ko',
    'jquery',
    'Magento_Checkout/js/model/quote',
    'uiComponent'

], function (ko, $, quote, Component) {
    'use strict';
    var shipMessage = window.checkoutConfig.ship_message;
    return Component.extend({
        defaults: {
            template: 'Namespace_Module/checkout/shipping/shipmessage-block'
        },
        isMessage: function () {
                if(shipMessage != ""){
                  return 1;
                } else {
                  return 0;
                }
         },
        getMessage: function() {
            return shipMessage;
        }
    });
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.