Loading...

Shipping Bar In Minicart In Magento

Pravin Prajapati  ·   19 Dec 2022
Shipping Bar In Minicart In Magento
service-banner

Steps to create a free shipping bar

Create Vendor & Module directory for creating module

If you have already the module then ignore the first 4 steps

(1)  Create Vendor & Module directory as follow :

->  app/code/Elightwalk/CustomGrid

(2) Create a registration.php file at the following location:

->   app/code/Elightwalk/CustomGrid/registration.php

php

\Magento\Framework\Component\ComponentRegistrar::register(

          \Magento\Framework\Component\ComponentRegistrar::MODULE,

          'Elightwalk_CustomGrid',

           __DIR__

);

(3) Create a module.xml file at the following location:

->   app/code/Elightwalk/CustomGrid/etc/module.xml

xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">

        <module name="Elightwalk_CustomGrid" setup_version="1.0.0">

                   <sequence>

                           <module name="Magento_Checkout"/>

                                    <module name="Magento_Tax"/>

                  </sequence>

         </module>

</config>

In the <sequence> element add the Magento core modules that you want to load before the current module.

(4) Create a routes.xml file at the following location:

->   app/code/Elightwalk/CustomGrid/etc/adminhtml

xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">

       <router id="admin">

                <route id="elightwalk_customgrid" frontName="elightwalk_customgrid">

                         <module name="Elightwalk_CustomGrid"/>

              </route>

      </router>

</config>

php bin/magento setup:upgrade

Run the following command to check your module enable or disable

  • php bin/magento module:status
  • php bin/magento module:enable Elightwalk_CustomGrid   

Then

  • php bin/magento setup:upgrade
  • php bin/magento setup:di:compile

Add a New Block For The Shipping Bar in The Minicart Section

(5) Extend the default.xml layout to add a shipping bar block at the following location:

->  app/code/Elightwalk/CustomGrid/view/frontend/layout/default.xml

xml
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<css src="Elightwalk_CustomGrid::css/miniprogress.css"/>
</head>
<body>
    <referenceContainer name="minicart.addons">
        <block class="Elightwalk\CustomGrid\Block\Cart\Sidebar" name="shipping_bar" template="Elightwalk_CustomGrid::cart/minicart.phtml">
            <arguments>
                <argument name="jsLayout" xsi:type="array">
                    <item name="components" xsi:type="array">
                        <item name="minicart-addons" xsi:type="array">
                            <item name="component" xsi:type="string">Elightwalk_CustomGrid/js/view/minicartaddons</item>
                            <item name="config" xsi:type="array">
                                <item name="template" xsi:type="string">Elightwalk_CustomGrid/minicartaddons/content</item>
                            </item>
                        </item>
                    </item>
                </argument>
            </arguments>
        </block>
    </referenceContainer>
</body>
</page>

(6) Create a Sidebar.php file at the following location:

->   app/code/Elightwalk/CustomGrid/Block/Cart/Sidebar.php

php

<?php

namespace Elightwalk\CustomGrid\Block\Cart;

 

use Magento\Framework\View\Element\Template;

 

class Sidebar extends Template

{

          /**

          *   Sidebar constructor.

          *   @param Template\Context $context

          *   @param array $data

          */

          public function __construct(

                    Template\Context $context,

                    array $data = []

          ) {

                    parent::__construct($context, $data);

         }

}

Remember case sensitivity of your file and folder name

Create a Template To Render The Content of The Knockout js Template File

(7) Create a minicart.phtml file at the following location:

->  app/code/Elightwalk/CustomGrid/view/frontend/templates/cart/minicart.phtml

xml

<div id="cart-page">

     <div id="block-cart-list" data-bind="scope:'minicart-addons'" class="block">

          <!-- ko template: getTemplate() --><!-- /ko -->

          <script type="text/x-magento-init">

            {

                    "#block-cart-list": {

                    "Magento_Ui/js/core/app": <?php /* @escapeNotVerified */ echo $block->getJsLayout();?>

             },

            "*": {

                      "Magento_Ui/js/block-loader": "<?= /* @escapeNotVerified */ $block->getViewFileUrl('images/loader-1.gif') ?>"

              }

         </script>

     </div>

</div>

(8) Create a minicartaddons.js file at the following location:

->   app/code/Elightwalk/CustomGrid/view/frontend/web/js/view/minicartaddons.js

js

define([

              'ko',

              'uiComponent',

             'Magento_Customer/js/customer-data',

     ], function (ko, Component, customerData) {

            'use strict';

             var subtotalAmount;

            var maxPrice = 100;

            var percentage;

            return Component.extend({

            displaySubtotal: ko.observable(true),

           maxprice: '$' + maxPrice.toFixed(2),

           /**

          * @override

          */

         initialize: function () {

               this._super();

               this.cart = customerData.get('cart');

         },

         getTotalCartItems: function () {

                return customerData.get('cart')().summary_count;

          },

         getpercentage: function () {

              subtotalAmount = customerData.get('cart')().subtotalAmount;

              if (subtotalAmount > maxPrice) {

                   subtotalAmount = maxPrice;

             }

              percentage = ((subtotalAmount * 100) / maxPrice);

                      return percentage;

              }

       });

});

(9) Create a content.html file at the following location:

->   app/code/Elightwalk/CustomGrid/view/frontend/web/template/minicartaddons/content.html

xml

<div class="component-wrapper" data-bind="if: getTotalCartItems() > 0">

          <h4 data-bind="text : getpercentage() < 100 ?'Free shipping' : 'Eligible for free shipping!'"></h4>

          <span data-bind="html: cart().subtotal"></span><span> / </span><span data-bind="text: maxprice"></span>

         <div class="minprogress" id="progress">

                  <div class="minprogress-active" id="child-progress" data-bind="style: { width: getpercentage() + '%' } ">                     </div>

       </div>

</div>

Create Less File For The Progress Bar

(10) LESS vs. CSS

LESS simplifies the management of a large volume of CSS styles and makes CSS more flexible, which are its main advantages.

css

div.minprogress {

          border: 1px solid #a5a5a5;

          height: 10px;

          border-radius: 5px;

          position: relative;

 

          .minprogress-active {

                    position: absolute;

                    background-color: #000000;

                    height: 10px;

                    border-radius: 5px;

          }

}

(11) Create a system.xml file to add a configuration menu to the admin panel

Create system.xml to add a new tab and section for the configuration of the shipping bar under store > configuration menu at the following location by adding the code snippet given below:

->   app/code/Elightwalk/CustomGrid/etc/adminhtml/system.xml

xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">

     <system>

            <tab id="elightwalk" translate="label" sortOrder="1000">

                   <label>ELIGHTWALK</label>

            </tab>

          <section id="customgrid" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">

               <label>CustomGrid</label>

                <tab>elightwalk</tab>

                <resource>Elightwalk_CustomGrid::customgrid_configuration</resource>

              <group id="shippingsection" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">

                      <label>Shipping Bar</label>

                      <field id="shipping_bar" translate="label comment" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">

                                <label>Max Price</label>

                               <comment>Set Maximum price for free shipping.</comment>

                      </field>

               </group>

         </section>

    </system>

</config>

(12) Create a config.xml file to define a default value

Create a config.xml file to set a default maximum price value of the shipping bar at the following location by adding the code given below:

->   app/code/Elightwalk/CustomGrid//etc/config.xml

xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">

         <default>

             <shippingbar>

                     <shippingsection>

                                  <shipping_bar>100</shipping_bar>

                    </shippingsection>

          </shippingbar>

      </default>

</config>

configuration menu will appear at the store > configuration menu.

Now, we are going to fetch the default value of max price which is set in the admin panel and will reflect this in the shipping bar.

(13) Create a helper to get a config value of the shipping bar

->   app/code/Elightwalk/CustomGrid/Helper/Data.php

<?php

namespace Elightwalk\CustomGrid\Helper;

use Magento\Framework\App\Helper\AbstractHelper;

class Data extends AbstractHelper

{

          const PRICE_SHIPPING_BAR = 'shippingbar/shippingsection/shipping_bar';

          /**

          * Return if maximum price for shipping bar

          * @return int

           */

           public function getPriceForShippingBar()

           {

                   return $this->scopeConfig->getValue(

                            self::PRICE_SHIPPING_BAR,

                           \Magento\Store\Model\ScopeInterface::SCOPE_STORE

                    );

            }

}

Use the helper to assign the config value of the shipping bar to the block

Replace the content of the app/code/Elightwalk/CustomGrid/Block/Cart/Sidebar.php file with the code snippet given below:

php

<?php

namespace Elightwalk\CustomGrid\Block\Cart;

use Magento\Framework\View\Element\Template;

class Sidebar extends Template

{

          /**

          * @var \Kiwicommerce\Jobs\Helper\Data

          */

            private $helper;

 

            /**

            * Sidebar constructor.

           * @param Template\Context $context

           * @param \Kiwicommerce\Jobs\Helper\Data $helper

           * @param array $data

           */

           public function __construct(

                     Template\Context $context,

                      \Kiwicommerce\Shippingbar\Helper\Data $helper,

                       array $data = []

           ) {

                 parent::__construct($context, $data);

                 $this->helper = $helper;

              }

              public function getConfigForShippingBar()

             {

                         return $this->helper->getPriceForShippingBar();

             }

}

Add the following code in the app/code/Elightwalk/CustomGrid/view/frontend/template/cart/minicart.phtml file to assign the config value to the javascript variable.

js

<script>

           maxpriceShipping = <?= /* @escapeNotVerified */ $this->getConfigForShippingBar() ?>;

</script>

php

<div id="cart-page">

          <div id="block-cart-list" data-bind="scope:'minicart-addons'" class="block">

                     <!-- ko template: getTemplate() --><!-- /ko -->

                     <script>

                             maxpriceShipping = <?= /* @escapeNotVerified */ $this->getConfigForShippingBar() ?>;

                    </script>

                   <script type="text/x-magento-init">

                     {

                            "#block-cart-list": {

                                    "Magento_Ui/js/core/app": <?php /* @escapeNotVerified */ echo $block->getJsLayout();?>

                              },

                              "*": {

                                             "Magento_Ui/js/block-loader": “<?= /* @escapeNotVerified */ $block->getViewFileUrl('images/loader-1.gif') ?>”

                               }

                      }

                    </script>

          </div>

</div>

app/code/Elightwalk/CustomGrid//view/frontend/web/js/view/minicartaddons.js

Replace the following line of code:

  • var maxPrice = 100;

With the code given below:

  • var maxPrice = maxpriceShipping;

Then apply cache clean cmd

  • php bin/magento cache:clean

If your changes not apply then try setup upgrade, setup compile and static:content:deploy cmd

  • php bin/magento setup:upgrade
  • php bin/magento setup:di:compile
  • php bin/magento setup:static-content:deploy -f

 

Then, change the price limit from the backend and show the shipping bar limit in the frontend minibar.

In conclusion, mastering the art of creating an exceptional grid in Magento can significantly enhance your e-commerce store's performance. Take advantage of the tips and techniques shared in this guide to build a visually appealing and efficient grid, improving user experience and driving higher conversions. Start optimizing your grid today and elevate your online business to new heights!

Contact us:+91 8128405131

Email send us at hello@elightwalk.com

Pravin Prajapati
Full Stack Developer

Expert in frontend and backend development, combining creativity with sharp technical knowledge. Passionate about keeping up with industry trends, he implements cutting-edge technologies, showcasing strong problem-solving skills and attention to detail in crafting innovative solutions.

Most Visited Blog

Everything You Need to Know About Checkout/Cart Page Summary Definition of checkout/cart page

Uncover a thorough grasp of the Checkout/Cart Page summary. Dive into all you need to know about this e-commerce element, learning its definition and importance for a smooth online purchasing experience.

How to Clear Shopping Cart in Magento 2

Discover a quick and simple approach to emptying your Magento 2 shopping basket. Streamline your shopping experience by learning how to easily delete things and refresh your basket.

How to get cart discount amount in minicart in Magento 2

Improve your Magento 2 shop by learning how to quickly obtain the cart discount amount within the minicart. Discover how to improve your user experience with visible and dynamic discount information.