In this post, we will check how to display old price, discount percentage and saved amount to minicart to checkout cart products.
We will,
-- Display Total saving amount in Minicart
-- Display Discount amount in Minicart
-- Display New column (Save) on checkout cart page and display saving amount for cart itemns.
-- Display Old Price on checkout page at cart items in sidebar.
-- Display Old Price on checkout/cart page at cart items in table display.
-- Display total savings on checkout cart and checkout page below order total.
-- Display additional product attribute (manufacturer name) on checkout/cart page in cart items table display.
-- Display additional product attribute (manufacturer name) on checkout page at cart items in sidebar.
You can find complete module on Github.
Add registration.php file in it:
<?php use Magento\Framework\Component\ComponentRegistrar; ComponentRegistrar::register( ComponentRegistrar::MODULE, 'Magelearn_Checkout', __DIR__ );Add composer.json file in it:
{ "name": "magelearn/module-checkout", "description": "Display Old Price, Discount Percentage and Saved Amount to Minicart Products.", "type": "magento2-module", "license": "OSL-3.0", "authors": [ { "email": "info@mage2gen.com", "name": "Mage2Gen" }, { "email": "vijaymrami@gmail.com", "name": "vijay rami" } ], "minimum-stability": "dev", "autoload": { "files": [ "registration.php" ], "psr-4": { "Magelearn\\Checkout\\": "" } } }
<?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="Magelearn_Checkout" setup_version="0.0.1" > <sequence>Magento_Checkout</sequence> </module> </config>
app/code/Magelearn/Checkout/etc/
folder.<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Catalog:etc/catalog_attributes.xsd"> <group name="quote_item"> <attribute name="regular_price_value"/> <attribute name="current_price_value"/> <attribute name="regular_price"/> <attribute name="discount_percentage"/> <attribute name="saved_amount"/> <attribute name="saved_amount_value"/> <attribute name="manufacturer"/> </group> </config>
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\Checkout\CustomerData\Cart"> <plugin name="magelearn_advancecart_grand_total" type="Magelearn\Checkout\Plugin\Checkout\CustomerData\Cart"/> </type> <type name="Magento\Checkout\CustomerData\DefaultItem"> <plugin name="AddAttPlug" type="Magelearn\Checkout\Plugin\DefaultItem" disabled="false" sortOrder="10"/> </type> </config>
<?php namespace Magelearn\Checkout\Plugin; use Magento\Framework\Pricing\PriceCurrencyInterface as CurrencyInterface; use Magento\Quote\Model\Quote\Item; class DefaultItem { protected $currencyInterface; protected $productFactory; protected $_logger; public function __construct( CurrencyInterface $currencyInterface, \Magento\Catalog\Model\ProductFactory $productFactory, \Psr\Log\LoggerInterface $logger ) { $this->currencyInterface = $currencyInterface; $this->productFactory = $productFactory; $this->_logger = $logger; } public function aroundGetItemData($subject, \Closure $proceed, Item $item) { $data = $proceed($item); $atts = []; $discount = 0; $save = 0; $product_type = $item->getProduct()->getTypeId(); $sku = $item->getProduct()->getSku(); $qty = $item->getQty(); //$this->_logger->debug($sku); if($product_type == 'configurable') { $product = $this->productFactory->create(); $productdata = $product->loadByAttribute('sku', $sku); $currentPrice = $productdata->getPriceInfo()->getPrice('final_price')->getAmount()->getValue(); $originalPrice = $productdata->getPriceInfo()->getPrice('regular_price')->getAmount()->getValue(); } else { $currentPrice = $item->getProduct()->getPriceInfo()->getPrice('final_price')->getAmount()->getValue(); $originalPrice = $item->getProduct()->getPriceInfo()->getPrice('regular_price')->getAmount()->getValue(); } if ($currentPrice != $originalPrice) { $discount = round((($originalPrice - $item->getPrice()) / $originalPrice) * 100, 0); $save = ($originalPrice - $currentPrice) * $qty; } $atts = [ "regular_price_value" => $originalPrice, "regular_price" => $this->currencyInterface->format($originalPrice, false, 2), "discount_percentage" => $discount, "saved_amount" => $this->currencyInterface->format($save, false, 2), "saved_amount_value" => $save ]; return array_merge($data, $atts); } public function getLoadProduct($id) { return $this->_productloader->create()->load($id); } }
As per etc/frontend/di.xml file add plugin file at app/code/Magelearn/Checkout/Plugin/Checkout/CustomerData/Cart.php
<?php namespace Magelearn\Checkout\Plugin\Checkout\CustomerData; class Cart { protected $checkoutSession; protected $checkoutHelper; protected $quote; /** * @var \Magento\Framework\Pricing\Helper\Data */ protected $priceHelper; protected $_logger; public function __construct( \Magento\Checkout\Model\Session $checkoutSession, \Magento\Checkout\Helper\Data $checkoutHelper, \Magento\Framework\Pricing\Helper\Data $priceHelper, \Psr\Log\LoggerInterface $logger ) { $this->checkoutSession = $checkoutSession; $this->checkoutHelper = $checkoutHelper; $this->priceHelper = $priceHelper; $this->_logger = $logger; } /** * Get active quote. * * @return Quote */ protected function getQuote() { if ($this->quote === null) { $this->quote = $this->checkoutSession->getQuote(); } return $this->quote; } protected function getDiscountAmount() { $discountAmount = 0; foreach($this->getQuote()->getAllVisibleItems() as $item){ $discountAmount += ($item->getDiscountAmount() ? $item->getDiscountAmount() : 0); } return $discountAmount; } /** * Add grand total to result * * @param \Magento\Checkout\CustomerData\Cart $subject * @param array $result * @return array */ public function afterGetSectionData( \Magento\Checkout\CustomerData\Cart $subject, $result ) { $savedAmount = 0; $items = $this->getQuote()->getAllVisibleItems(); if (is_array($result['items'])) { foreach ($result['items'] as $key => $itemAsArray) { $savedAmount += $itemAsArray['saved_amount_value'] ?? 0; } } $result['saved_amount_no_html'] = $savedAmount; $result['discount_amount_no_html'] = -$this->getDiscountAmount(); $result['discount_amount'] = $this->checkoutHelper->formatPrice(-$this->getDiscountAmount()); $result['saved_amount'] = $this->checkoutHelper->formatPrice($savedAmount); return $result; } }
<?xml version="1.0"?> <!-- /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ --> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="minicart"> <block class="Magento\Checkout\Block\Item\Price\Renderer" name="checkout.cart.item.price.sidebar" template="Magento_Checkout::cart/item/price/sidebar.phtml"/> <arguments> <argument name="jsLayout" xsi:type="array"> <item name="components" xsi:type="array"> <item name="minicart_content" xsi:type="array"> <item name="children" xsi:type="array"> <item name="item.renderer" xsi:type="array"> <item name="children" xsi:type="array"> <item name="checkout.cart.item.price.sidebar" xsi:type="array"> <item name="component" xsi:type="string">uiComponent</item> <item name="config" xsi:type="array"> <item name="template" xsi:type="string">Magelearn_Checkout/minicart/item/price</item> <item name="displayArea" xsi:type="string">priceSidebar</item> </item> </item> </item> </item> </item> </item> </item> </argument> </arguments> </referenceBlock> </body> </page>
<!-- /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ --> <div class="price-container"> <span class="price-wrapper" data-bind="html: price"></span> <!-- ko if: item.regular_price_value != item.product_price_value --> <div class="old-price-wrapper" style="display:flex;"> <span class="old-price"> <span class="price" data-bind="html: item.regular_price"></span> </span> <span class="discount-percent" style="margin-left: 7px" data-bind="html: item.discount_percentage + '% off'"></span> </div> <span class="saved-amount" data-bind="html: 'Save: ' + item.saved_amount"></span> <!-- /ko --> </div>
Now we will check how to display total savings and Discount Amount in minicart after the subtotal text.
<?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="minicart"> <arguments> <argument name="jsLayout" xsi:type="array"> <item name="components" xsi:type="array"> <item name="minicart_content" xsi:type="array"> <item name="children" xsi:type="array"> <item name="extra.save.container" xsi:type="array"> <item name="component" xsi:type="string">uiComponent</item> <item name="config" xsi:type="array"> <item name="displayArea" xsi:type="string">subtotalContainer</item> </item> <item name="children" xsi:type="array"> <item name="subtotalextra" xsi:type="array"> <item name="component" xsi:type="string">Magento_Checkout/js/view/checkout/minicart/subtotal/totals</item> <item name="config" xsi:type="array"> <item name="template" xsi:type="string">Magelearn_Checkout/minicart/extra</item> </item> <item name="children" xsi:type="array"> <item name="subtotalextra.save" xsi:type="array"> <item name="component" xsi:type="string">Magento_Checkout/js/view/checkout/minicart/subtotal/totals</item> <item name="config" xsi:type="array"> <item name="template" xsi:type="string">Magelearn_Checkout/minicart/extra/save</item> </item> </item> </item> </item> </item> </item> <item name="discount.container" xsi:type="array"> <item name="component" xsi:type="string">uiComponent</item> <item name="config" xsi:type="array"> <item name="displayArea" xsi:type="string">subtotalContainer</item> </item> <item name="children" xsi:type="array"> <item name="subtotal" xsi:type="array"> <item name="component" xsi:type="string">Magento_Checkout/js/view/checkout/minicart/subtotal/totals</item> <item name="config" xsi:type="array"> <item name="template" xsi:type="string">Magelearn_Checkout/minicart/discount</item> </item> <item name="children" xsi:type="array"> <item name="subtotal.totals" xsi:type="array"> <item name="component" xsi:type="string">Magento_Checkout/js/view/checkout/minicart/subtotal/totals</item> <item name="config" xsi:type="array"> <item name="template" xsi:type="string">Magelearn_Checkout/minicart/discount/inner</item> </item> </item> </item> </item> </item> </item> </item> </item> </item> </argument> </arguments> </referenceBlock> </body> </page>
<!-- ko if: (cart().saved_amount_no_html > 0) --> <div class="subtotal"> <span class="label"> <!-- ko i18n: 'Total Save' --><!-- /ko --> </span> <!-- ko foreach: elems --> <!-- ko template: getTemplate() --><!-- /ko --> <!-- /ko --> </div> <!-- /ko -->
<div class="amount price-container"> <span class="price-wrapper" data-bind="html: cart().saved_amount"></span> </div>
We will also add some files to display discount amount in minicart sidebar items.
<!-- ko if: (cart().discount_amount_no_html < 0) --> <div class="subtotal"> <span class="label"> <!-- ko i18n: 'Discount' --><!-- /ko --> </span> <!-- ko foreach: elems --> <!-- ko template: getTemplate() --><!-- /ko --> <!-- /ko --> </div> <!-- /ko -->
<div class="amount price-container"> <span class="price-wrapper" data-bind="html: cart().discount_amount"></span> </div>
Now we will check how to display extra attribute (Product manufacturer) on checkout/cart page in cart items table display.
For that we will add app/code/Magelearn/Checkout/view/frontend/layout/checkout_cart_index.xml file.
<?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="checkout.cart.form"> <action method="setTemplate"> <argument name="template" xsi:type="string">Magelearn_Checkout::cart/form.phtml</argument> </action> </referenceBlock> <referenceBlock name="additional.product.info"> <block class="Magelearn\Checkout\Block\CartItemAdditionalBlock" name="magelearn.checkout.cart.item.additional" template="Magelearn_Checkout::product_additional.phtml" before="-"> </block> </referenceBlock> <referenceBlock name="checkout.cart.totals"> <arguments> <argument name="jsLayout" xsi:type="array"> <item name="components" xsi:type="array"> <item name="block-totals" xsi:type="array"> <item name="children" xsi:type="array"> <item name="checkout-mycustomtext" xsi:type="array"> <item name="component" xsi:type="string">Magelearn_Checkout/js/view/checkout-mycustomtext</item> <item name="config" xsi:type="array"> <item name="sortOrder" xsi:type="string">0</item> </item> </item> </item> </item> </item> </argument> </arguments> </referenceBlock> </body> </page>
Now as per highlighted code above, we will first add our block file at app/code/Magelearn/Checkout/Block/CartItemAdditionalBlock.php file.
<?php namespace Magelearn\Checkout\Block; use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Api\Data\ProductInterfaceFactory; use Magento\Catalog\Model\Product; use Magento\Checkout\Block\Cart\Additional\Info as AdditionalBlockInfo; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\View\Element\Template as ViewTemplate; use Magento\Framework\View\Element\Template\Context; /** * Class CartItemAdditionalBlock */ class CartItemAdditionalBlock extends ViewTemplate { /** * Product * * @var ProductInterface|null */ protected $product = null; /** * Product Factory * * @var ProductInterfaceFactory */ protected $productFactory; /** * CartItemAdditionalBlock constructor * * @param Context $context * @param ProductInterfaceFactory $productFactory */ public function __construct( Context $context, ProductInterfaceFactory $productFactory ) { parent::__construct($context); $this->productFactory = $productFactory; } /** * Get Product Brand Text * * @return string */ public function getProductBrand(): string { $product = $this->getProduct(); /** @var Product $product */ $Manufacturer = (string)$product->getResource()->getAttribute('manufacturer')->getFrontend()->getValue($product); return $Manufacturer; } /** * Get product from quote item * * @return ProductInterface */ public function getProduct(): ProductInterface { try { $layout = $this->getLayout(); } catch (LocalizedException $e) { $this->product = $this->productFactory->create(); return $this->product; } /** @var AdditionalBlockInfo $block */ $block = $layout->getBlock('additional.product.info'); if ($block instanceof AdditionalBlockInfo) { $item = $block->getItem(); $this->product = $item->getProduct(); } return $this->product; } }
And template file at app/code/Magelearn/Checkout/view/frontend/templates/product_additional.phtml
<div class="product-brand"> <p><?php echo $block->getProductBrand(); ?></p> </div>
Now, we will check how to add extra column (save amount) on checkout/cart page for cart items table display.
Now as per defined in checkout_cart_index.xml file, we will override checkout/cart form.phtml file.
for that copy file from vendor/magento/module-checkout/view/frontend/templates/cart/form.phtml and add inside app/code/Magelearn/Checkout/view/frontend/templates/cart/form.phtml
Now modify code as per highlighted below. this will add new headings (Save) column in cart items table display.
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ // phpcs:disable Magento2.Templates.ThisInTemplate /** @var $block \Magento\Checkout\Block\Cart\Grid */ ?> <?php $mergedCells = ($this->helper(Magento\Tax\Helper\Data::class)->displayCartBothPrices() ? 2 : 1); ?> <?= $block->getChildHtml('form_before') ?> <form action="<?= $block->escapeUrl($block->getUrl('checkout/cart/updatePost')) ?>" method="post" id="form-validate" data-mage-init='{"Magento_Checkout/js/action/update-shopping-cart": {"validationURL" : "<?= $block->escapeUrl($block->getUrl('checkout/cart/updateItemQty')) ?>", "updateCartActionContainer": "#update_cart_action_container"} }' class="form form-cart"> <?= $block->getBlockHtml('formkey') ?> <div class="cart table-wrapper<?= $mergedCells == 2 ? ' detailed' : '' ?>"> <?php if ($block->getPagerHtml()): ?> <div class="cart-products-toolbar cart-products-toolbar-top toolbar" data-attribute="cart-products-toolbar-top"><?= $block->getPagerHtml() ?> </div> <?php endif ?> <table id="shopping-cart-table" class="cart items data table" data-mage-init='{"shoppingCart":{"emptyCartButton": ".action.clear", "updateCartActionContainer": "#update_cart_action_container"}}'> <caption class="table-caption"><?= $block->escapeHtml(__('Shopping Cart Items')) ?></caption> <thead> <tr> <th class="col item" scope="col"><span><?= $block->escapeHtml(__('Item')) ?></span></th> <th class="col price" scope="col"><span><?= $block->escapeHtml(__('Price')) ?></span></th> <th class="col save" scope="col"><span><?= $block->escapeHtml(__('Save')) ?></span></th> <th class="col qty" scope="col"><span><?= $block->escapeHtml(__('Qty')) ?></span></th> <th class="col subtotal" scope="col"><span><?= $block->escapeHtml(__('Subtotal')) ?></span></th> </tr> </thead> <?php foreach ($block->getItems() as $_item): ?> <?= $block->getItemHtml($_item) ?> <?php endforeach ?> </table> <?php if ($block->getPagerHtml()): ?> <div class="cart-products-toolbar cart-products-toolbar-bottom toolbar" data-attribute="cart-products-toolbar-bottom"><?= $block->getPagerHtml() ?> </div> <?php endif ?> </div> <div class="cart main actions"> <?php if ($block->getContinueShoppingUrl()): ?> <a class="action continue" href="<?= $block->escapeUrl($block->getContinueShoppingUrl()) ?>" title="<?= $block->escapeHtml(__('Continue Shopping')) ?>"> <span><?= $block->escapeHtml(__('Continue Shopping')) ?></span> </a> <?php endif; ?> <?php if ($block->getViewModel()->isClearShoppingCartEnabled()): ?> <button type="button" name="update_cart_action" data-cart-empty="" value="empty_cart" title="<?= $block->escapeHtml(__('Clear Shopping Cart')) ?>" class="action clear" id="empty_cart_button"> <span><?= $block->escapeHtml(__('Clear Shopping Cart')) ?></span> </button> <?php endif ?> <button type="submit" name="update_cart_action" data-cart-item-update="" value="update_qty" title="<?= $block->escapeHtml(__('Update Shopping Cart')) ?>" class="action update"> <span><?= $block->escapeHtml(__('Update Shopping Cart')) ?></span> </button> <input type="hidden" value="" id="update_cart_action_container" data-cart-item-update=""/> </div> </form> <?= $block->getChildHtml('checkout.cart.order.actions') ?> <?= $block->getChildHtml('shopping.cart.table.after') ?>
Now to display save amount for cart items in checkout cart table display we will first modify layout file.
we will modify checkout_cart_item_renderers.xml file and will override template for different product types.
Add app/code/Magelearn/Checkout/view/frontend/layout/checkout_cart_item_renderers.xml file.
<?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <!-- override checkout cart item template --> <referenceBlock name="checkout.cart.form"> <action method="setOverriddenTemplates"> <argument name="jsLayout" xsi:type="array"> <!-- list override templates --> <item name="default" xsi:type="string">Magelearn_Checkout::cart/item/default.phtml</item> <item name="simple" xsi:type="string">Magelearn_Checkout::cart/item/default.phtml</item> <item name="configurable" xsi:type="string">Magelearn_Checkout::cart/item/default_configurable.phtml</item> <item name="bundle" xsi:type="string">Magelearn_Checkout::cart/item/default.phtml</item> <item name="downloadable" xsi:type="string">Magelearn_Checkout::cart/item/default.phtml</item> <item name="grouped" xsi:type="string">Magelearn_Checkout::cart/item/default.phtml</item> <item name="virtual" xsi:type="string">Magelearn_Checkout::cart/item/default.phtml</item> </argument> </action> </referenceBlock> </body> </page>
As per highlighted code above, we will add our template path as per path defined.
Add app/code/Magelearn/Checkout/view/frontend/templates/cart/item/default.phtml file.
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ // phpcs:disable Magento2.Templates.ThisInTemplate // phpcs:disable Magento2.Files.LineLength.MaxExceeded /** @var $block \Magento\Checkout\Block\Cart\Item\Renderer */ $_item = $block->getItem(); $product = $_item->getProduct(); $isVisibleProduct = $product->isVisibleInSiteVisibility(); /** @var \Magento\Msrp\Helper\Data $helper */ $helper = $this->helper(Magento\Msrp\Helper\Data::class); $canApplyMsrp = $helper->isShowBeforeOrderConfirm($product) && $helper->isMinimalPriceLessMsrp($product); ?> <tbody class="cart item"> <tr class="item-info"> <td data-th="<?= $block->escapeHtml(__('Item')) ?>" class="col item"> <?php if ($block->hasProductUrl()) :?> <a href="<?= $block->escapeUrl($block->getProductUrl()) ?>" title="<?= $block->escapeHtml($block->getProductName()) ?>" tabindex="-1" class="product-item-photo"> <?php else :?> <span class="product-item-photo"> <?php endif;?> <?= $block->getImage($block->getProductForThumbnail(), 'cart_page_product_thumbnail')->toHtml() ?> <?php if ($block->hasProductUrl()) :?> </a> <?php else :?> </span> <?php endif; ?> <div class="product-item-details"> <strong class="product-item-name"> <?php if ($block->hasProductUrl()) :?> <a href="<?= $block->escapeUrl($block->getProductUrl()) ?>"><?= $block->escapeHtml($block->getProductName()) ?></a> <?php else :?> <?= $block->escapeHtml($block->getProductName()) ?> <?php endif; ?> </strong> <?php if ($_options = $block->getOptionList()) :?> <dl class="item-options"> <?php foreach ($_options as $_option) :?> <?php $_formatedOptionValue = $block->getFormatedOptionValue($_option) ?> <dt><?= $block->escapeHtml($_option['label']) ?></dt> <dd> <?php if (isset($_formatedOptionValue['full_view'])) :?> <?= $block->escapeHtml($_formatedOptionValue['full_view']) ?> <?php else :?> <?= $block->escapeHtml($_formatedOptionValue['value'], ['span', 'a']) ?> <?php endif; ?> </dd> <?php endforeach; ?> </dl> <?php endif;?> <?php if ($messages = $block->getMessages()) :?> <?php foreach ($messages as $message) :?> <div class= "cart item message <?= $block->escapeHtmlAttr($message['type']) ?>"> <div><?= $block->escapeHtml($message['text']) ?></div> </div> <?php endforeach; ?> <?php endif; ?> <?php $addInfoBlock = $block->getProductAdditionalInformationBlock(); ?> <?php if ($addInfoBlock) :?> <?= $addInfoBlock->setItem($_item)->toHtml() ?> <?php endif;?> </div> </td> <?php if ($canApplyMsrp) :?> <td class="col msrp" data-th="<?= $block->escapeHtml(__('Price')) ?>"> <span class="pricing msrp"> <span class="msrp notice"><?= $block->escapeHtml(__('See price before order confirmation.')) ?></span> <?php $helpLinkId = 'cart-msrp-help-' . $_item->getId(); ?> <a href="#" class="action help map" id="<?= ($block->escapeHtmlAttr($helpLinkId)) ?>" data-mage-init='{"addToCart":{ "helpLinkId": "#<?= $block->escapeJs($block->escapeHtml($helpLinkId)) ?>", "productName": "<?= $block->escapeJs($block->escapeHtml($product->getName())) ?>", "showAddToCart": false } }' > <span><?= $block->escapeHtml(__("What's this?")) ?></span> </a> </span> </td> <?php else :?> <td class="col price" data-th="<?= $block->escapeHtml(__('Price')) ?>"> <?= $block->getUnitPriceHtml($_item) ?> </td> <?php endif; ?> <td class="col save" data-th="Save"> <span class="td-span-save"> <span class="save-val"> <?php $save = 0; $qty = $_item->getQty(); $currentPrice = $product->getPriceInfo()->getPrice('final_price')->getAmount()->getValue(); $originalPrice = $product->getPriceInfo()->getPrice('regular_price')->getAmount()->getValue(); if ($currentPrice != $originalPrice) { $save = ($originalPrice - $currentPrice) * $qty; } ?> <?= $this->helper('Magento\Framework\Pricing\Helper\Data')->currency(number_format($save, 2), true, false); ?> </span> </span> </td> <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty')) ?>"> <div class="field qty"> <div class="control qty"> <label for="cart-<?= $block->escapeHtmlAttr($_item->getId()) ?>-qty"> <span class="label"><?= $block->escapeHtml(__('Qty')) ?></span> <input id="cart-<?= $block->escapeHtmlAttr($_item->getId()) ?>-qty" name="cart[<?= $block->escapeHtmlAttr($_item->getId()) ?>][qty]" data-cart-item-id="<?= $block->escapeHtmlAttr($_item->getSku()) ?>" value="<?= $block->escapeHtmlAttr($block->getQty()) ?>" type="number" size="4" step="any" title="<?= $block->escapeHtmlAttr(__('Qty')) ?>" class="input-text qty" data-validate="{required:true,'validate-greater-than-zero':true}" data-role="cart-item-qty"/> </label> </div> </div> </td> <td class="col subtotal" data-th="<?= $block->escapeHtml(__('Subtotal')) ?>"> <?php if ($canApplyMsrp) :?> <span class="cart msrp subtotal">--</span> <?php else :?> <?= $block->getRowTotalHtml($_item) ?> <?php endif; ?> </td> </tr> <tr class="item-actions"> <td colspan="4"> <div class="actions-toolbar"> <?= /* @noEscape */ $block->getActions($_item) ?> </div> </td> </tr> </tbody>
And for configurable items Add app/code/Magelearn/Checkout/view/frontend/templates/cart/item/default_configurable.phtml file.
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ // phpcs:disable Magento2.Templates.ThisInTemplate // phpcs:disable Magento2.Files.LineLength.MaxExceeded /** @var $block \Magento\Checkout\Block\Cart\Item\Renderer */ $_item = $block->getItem(); $product = $_item->getProduct(); $isVisibleProduct = $product->isVisibleInSiteVisibility(); /** @var \Magento\Msrp\Helper\Data $helper */ $helper = $this->helper(Magento\Msrp\Helper\Data::class); $canApplyMsrp = $helper->isShowBeforeOrderConfirm($product) && $helper->isMinimalPriceLessMsrp($product); ?> <tbody class="cart item"> <tr class="item-info"> <td data-th="<?= $block->escapeHtml(__('Item')) ?>" class="col item"> <?php if ($block->hasProductUrl()) :?> <a href="<?= $block->escapeUrl($block->getProductUrl()) ?>" title="<?= $block->escapeHtml($block->getProductName()) ?>" tabindex="-1" class="product-item-photo"> <?php else :?> <span class="product-item-photo"> <?php endif;?> <?= $block->getImage($block->getProductForThumbnail(), 'cart_page_product_thumbnail')->toHtml() ?> <?php if ($block->hasProductUrl()) :?> </a> <?php else :?> </span> <?php endif; ?> <div class="product-item-details"> <strong class="product-item-name"> <?php if ($block->hasProductUrl()) :?> <a href="<?= $block->escapeUrl($block->getProductUrl()) ?>"><?= $block->escapeHtml($block->getProductName()) ?></a> <?php else :?> <?= $block->escapeHtml($block->getProductName()) ?> <?php endif; ?> </strong> <?php if ($_options = $block->getOptionList()) :?> <dl class="item-options"> <?php foreach ($_options as $_option) :?> <?php $_formatedOptionValue = $block->getFormatedOptionValue($_option) ?> <dt><?= $block->escapeHtml($_option['label']) ?></dt> <dd> <?php if (isset($_formatedOptionValue['full_view'])) :?> <?= $block->escapeHtml($_formatedOptionValue['full_view']) ?> <?php else :?> <?= $block->escapeHtml($_formatedOptionValue['value'], ['span', 'a']) ?> <?php endif; ?> </dd> <?php endforeach; ?> </dl> <?php endif;?> <?php if ($messages = $block->getMessages()) :?> <?php foreach ($messages as $message) :?> <div class= "cart item message <?= $block->escapeHtmlAttr($message['type']) ?>"> <div><?= $block->escapeHtml($message['text']) ?></div> </div> <?php endforeach; ?> <?php endif; ?> <?php $addInfoBlock = $block->getProductAdditionalInformationBlock(); ?> <?php if ($addInfoBlock) :?> <?= $addInfoBlock->setItem($_item)->toHtml() ?> <?php endif;?> </div> </td> <?php if ($canApplyMsrp) :?> <td class="col msrp" data-th="<?= $block->escapeHtml(__('Price')) ?>"> <span class="pricing msrp"> <span class="msrp notice"><?= $block->escapeHtml(__('See price before order confirmation.')) ?></span> <?php $helpLinkId = 'cart-msrp-help-' . $_item->getId(); ?> <a href="#" class="action help map" id="<?= ($block->escapeHtmlAttr($helpLinkId)) ?>" data-mage-init='{"addToCart":{ "helpLinkId": "#<?= $block->escapeJs($block->escapeHtml($helpLinkId)) ?>", "productName": "<?= $block->escapeJs($block->escapeHtml($product->getName())) ?>", "showAddToCart": false } }' > <span><?= $block->escapeHtml(__("What's this?")) ?></span> </a> </span> </td> <?php else :?> <td class="col price" data-th="<?= $block->escapeHtml(__('Price')) ?>"> <?= $block->getUnitPriceHtml($_item) ?> </td> <?php endif; ?> <td class="col save" data-th="Save"> <span class="td-span-save"> <span class="save-val"> <?php $sku = $_item->getSku(); $qty = $_item->getQty(); $custom_helper = $this->helper(Magelearn\Checkout\Helper\Data::class); $productdata = $custom_helper->getProductBySku($sku); $currentPrice = $productdata->getPriceInfo()->getPrice('final_price')->getAmount()->getValue(); $originalPrice = $productdata->getPriceInfo()->getPrice('regular_price')->getAmount()->getValue(); $save = 0; if ($currentPrice != $originalPrice) { $save = ($originalPrice - $currentPrice) * $qty; } ?> <?= $this->helper('Magento\Framework\Pricing\Helper\Data')->currency(number_format($save, 2), true, false); ?> </span> </span> </td> <td class="col qty" data-th="<?= $block->escapeHtml(__('Qty')) ?>"> <div class="field qty"> <div class="control qty"> <label for="cart-<?= $block->escapeHtmlAttr($_item->getId()) ?>-qty"> <span class="label"><?= $block->escapeHtml(__('Qty')) ?></span> <input id="cart-<?= $block->escapeHtmlAttr($_item->getId()) ?>-qty" name="cart[<?= $block->escapeHtmlAttr($_item->getId()) ?>][qty]" data-cart-item-id="<?= $block->escapeHtmlAttr($_item->getSku()) ?>" value="<?= $block->escapeHtmlAttr($block->getQty()) ?>" type="number" size="4" step="any" title="<?= $block->escapeHtmlAttr(__('Qty')) ?>" class="input-text qty" data-validate="{required:true,'validate-greater-than-zero':true}" data-role="cart-item-qty"/> </label> </div> </div> </td> <td class="col subtotal" data-th="<?= $block->escapeHtml(__('Subtotal')) ?>"> <?php if ($canApplyMsrp) :?> <span class="cart msrp subtotal">--</span> <?php else :?> <?= $block->getRowTotalHtml($_item) ?> <?php endif; ?> </td> </tr> <tr class="item-actions"> <td colspan="4"> <div class="actions-toolbar"> <?= /* @noEscape */ $block->getActions($_item) ?> </div> </td> </tr> </tbody>
As per highlighted code above, we will add our helper file at app/code/Magelearn/Checkout/Helper/Data.php
<?php namespace Magelearn\Checkout\Helper; class Data extends \Magento\Framework\App\Helper\AbstractHelper { protected $productFactory; /** * @param \Magento\Framework\App\Helper\Context $context * @param \Magento\Catalog\Model\ProductFactory $productFactory, * @param array $data */ public function __construct( \Magento\Framework\App\Helper\Context $context, \Magento\Catalog\Model\ProductFactory $productFactory, array $data = [] ) { parent::__construct($context); $this->productFactory = $productFactory; } /** * Function for getting product by SKU * * @param string $sku, */ public function getProductBySku($sku) { $product = $this->productFactory->create(); $productdata = $product->loadByAttribute('sku', $sku); return $productdata; } }
Next we will check how to display additional data (Product manufacturer and original price) on checkout page in sidebar items
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\Checkout\Model\DefaultConfigProvider"> <plugin name="checkout-summary-product-attribs" type="Magelearn\Checkout\Plugin\Checkout\Model\DefaultConfigProvider" /> </type> </config>
Now as per highlighted code above, we will add our plugin file at app/code/Magelearn/Checkout/Plugin/Checkout/Model/DefaultConfigProvider.php
<?php namespace Magelearn\Checkout\Plugin\Checkout\Model; use Magento\Checkout\Model\Session as CheckoutSession; use Magento\Framework\Pricing\PriceCurrencyInterface as CurrencyInterface; class DefaultConfigProvider { /** * @var CheckoutSession */ protected $checkoutSession; protected $productFactory; protected $currencyInterface; /** * Constructor * * @param CheckoutSession $checkoutSession */ public function __construct( CheckoutSession $checkoutSession, \Magento\Catalog\Model\ProductFactory $productFactory, CurrencyInterface $currencyInterface ) { $this->checkoutSession = $checkoutSession; $this->productFactory = $productFactory; $this->currencyInterface = $currencyInterface; } public function afterGetConfig( \Magento\Checkout\Model\DefaultConfigProvider $subject, array $result ) { $items = $result['totalsData']['items']; foreach ($items as $index => $item) { $quoteItem = $this->checkoutSession->getQuote()->getItemById($item['item_id']); if($quoteItem) { $result['quoteItemData'][$index]['manufacturer'] = $quoteItem->getProduct()->getAttributeText('manufacturer'); $product_type = $quoteItem->getProduct()->getTypeId(); $sku = $quoteItem->getProduct()->getSku(); $qty = $quoteItem->getQty(); if($product_type == 'configurable') { $product = $this->productFactory->create(); $productdata = $product->loadByAttribute('sku', $sku); $result['quoteItemData'][$index]['current_price_value'] = $productdata->getPriceInfo()->getPrice('final_price')->getAmount()->getValue(); $result['quoteItemData'][$index]['regular_price_value'] = $productdata->getPriceInfo()->getPrice('regular_price')->getAmount()->getValue(); $originalPrice = $productdata->getPriceInfo()->getPrice('regular_price')->getAmount()->getValue() * $qty; $result['quoteItemData'][$index]['regular_price'] = $this->currencyInterface->format($originalPrice, false, 2); } else { $result['quoteItemData'][$index]['current_price_value'] = $quoteItem->getProduct()->getPriceInfo()->getPrice('final_price')->getAmount()->getValue(); $result['quoteItemData'][$index]['regular_price_value'] = $quoteItem->getProduct()->getPriceInfo()->getPrice('regular_price')->getAmount()->getValue(); $originalPrice = $quoteItem->getProduct()->getPriceInfo()->getPrice('regular_price')->getAmount()->getValue() * $qty; $result['quoteItemData'][$index]['regular_price'] = $this->currencyInterface->format($originalPrice, false, 2); } } } return $result; } }
Now we have data available to display on checkout page. Now we will start to modify layout file to display this data on checkout page.
Firt we will add app/code/Magelearn/Checkout/view/frontend/layout/checkout_index_index.xml file.
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="checkout.root"> <arguments> <argument name="jsLayout" xsi:type="array"> <item name="components" xsi:type="array"> <item name="checkout" xsi:type="array"> <item name="children" xsi:type="array"> <item name="sidebar" xsi:type="array"> <item name="children" xsi:type="array"> <item name="summary" xsi:type="array"> <item name="children" xsi:type="array"> <item name="itemsBefore" xsi:type="array"> <item name="component" xsi:type="string">uiComponent</item> <item name="children" xsi:type="array"> <!-- merge your components here --> <item name="checkout-mycustomtext" xsi:type="array"> <item name="component" xsi:type="string">Magelearn_Checkout/js/view/checkout-mycustomtext</item> </item> </item> </item> <item name="cart_items" xsi:type="array"> <item name="children" xsi:type="array"> <item name="details" xsi:type="array"> <item name="component" xsi:type="string">Magelearn_Checkout/js/view/summary/item/details</item> </item> </item> </item> </item> </item> </item> </item> </item> </item> </item> </argument> </arguments> </referenceBlock> </body> </page>
Now as per defined and code highlighted in above file, we will first check to diplay custom text (total save amount) in order summary below order total.
For that first we will add our JS component file at app/code/Magelearn/Checkout/view/frontend/web/js/view/checkout-mycustomtext.js
/** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ define([ 'jquery', 'ko', 'uiComponent', 'Magento_Checkout/js/model/quote', 'Magento_Checkout/js/checkout-data', 'Magento_Customer/js/customer-data', 'mage/translate'], function($, ko, Component, quote, checkoutData, customerData, $t){ return Component.extend({ initialize: function () { this._super(); }, defaults: { template: 'Magelearn_Checkout/sales/checkout/mycustomtext' }, getTotalSavings: function (){ var cartdata = customerData.get('cart'); //var customText = $t('Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged'); return cartdata().saved_amount; } }); });
In this file, we are getting custom data (saved_amount) from cart object. That we have added from app/code/Magelearn/Checkout/etc/frontend/di.xml file.
Now as per defined in checkout-mycustomtext.js file, we will add our template file at app/code/Magelearn/Checkout/view/frontend/web/template/sales/checkout/mycustomtext.html
<!-- ko if: cart().saved_amount_no_html > 0 --> <div class="subtotal checkout cart savings"> <span class="label"> <!-- ko i18n: 'Your Total Savings:' --><!-- /ko --> </span> <span class="price-wrapper" data-bind="html: getTotalSavings()" style="font-weight:bold;"></span> </div> <!-- /ko -->
Now as per defined in checkout_index_index.xml file, we will add our JS component at app/code/Magelearn/Checkout/view/frontend/web/js/view/summary/item/details.js and will display original price and manufacturer for items on checkout page.
/** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ define([ 'uiComponent', 'escaper' ], function (Component, escaper) { 'use strict'; var quoteItemData = window.checkoutConfig.quoteItemData; return Component.extend({ defaults: { template: 'Magelearn_Checkout/summary/item/details', allowedTags: ['b', 'strong', 'i', 'em', 'u'] }, quoteItemData: quoteItemData, /** * @param {Object} quoteItem * @return {String} */ getNameUnsanitizedHtml: function (quoteItem) { var txt = document.createElement('textarea'); txt.innerHTML = quoteItem.name; return escaper.escapeHtml(txt.value, this.allowedTags); }, /** * @param {Object} quoteItem * @return {String}Magento_Checkout/js/region-updater */ getValue: function (quoteItem) { return quoteItem.name; }, getManufacturer: function(quoteItem) { var item = this.getItem(quoteItem.item_id); return item.manufacturer; }, getRegularPrice: function(quoteItem) { var item = this.getItem(quoteItem.item_id); return item.regular_price_value; }, getRegularPriceHtml: function(quoteItem) { var item = this.getItem(quoteItem.item_id); return item.regular_price; }, getCurrentPrice: function(quoteItem) { var item = this.getItem(quoteItem.item_id); return item.current_price_value; }, getItem: function(item_id) { var itemElement = null; _.each(this.quoteItemData, function(element, index) { if (element.item_id == item_id) { itemElement = element; } }); return itemElement; } }); });
Now as per defined in above file, we will add template file at app/code/Magelearn/Checkout/view/frontend/web/template/summary/item/details.html
<!-- /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ --> <!-- ko foreach: getRegion('before_details') --> <!-- ko template: getTemplate() --><!-- /ko --> <!-- /ko --> <div class="product-item-details"> <div class="product-item-inner"> <div class="product-item-name-block"> <strong class="product-item-name" data-bind="html: getNameUnsanitizedHtml($parent)"></strong> <!-- ko if: (getManufacturer($parent))--> <strong class="product-item-manufacturer" data-bind="text: getManufacturer($parent)"></strong> <!-- /ko --> <div class="details-qty"> <span class="label"><!-- ko i18n: 'Qty' --><!-- /ko --></span> <span class="value" data-bind="text: $parent.qty"></span> </div> </div> <!-- ko foreach: getRegion('after_details') --> <!-- ko template: getTemplate() --><!-- /ko --> <!-- /ko --> <!-- ko if: (getCurrentPrice($parent) != getRegularPrice($parent)) --> <div class="old-price-wrapper" style="display:flex;"> <strike><span class="old-price"><span class="price" data-bind="text: getRegularPriceHtml($parent)"></span></span></strike> </div> <!-- /ko --> </div> <!-- ko if: (JSON.parse($parent.options).length > 0)--> <div class="product options" data-bind="mageInit: {'collapsible':{'openedState': 'active'}}"> <span data-role="title" class="toggle"><!-- ko i18n: 'View Details' --><!-- /ko --></span> <div data-role="content" class="content"> <strong class="subtitle"><!-- ko i18n: 'Options Details' --><!-- /ko --></strong> <dl class="item-options"> <!--ko foreach: JSON.parse($parent.options)--> <dt class="label" data-bind="text: label"></dt> <!-- ko if: ($data.full_view)--> <!-- ko with: {full_viewUnsanitizedHtml: $data.full_view}--> <dd class="values" data-bind="html: full_viewUnsanitizedHtml"></dd> <!-- /ko --> <!-- /ko --> <!-- ko ifnot: ($data.full_view)--> <!-- ko with: {valueUnsanitizedHtml: $data.value}--> <dd class="values" data-bind="html: valueUnsanitizedHtml"></dd> <!-- /ko --> <!-- /ko --> <!-- /ko --> </dl> </div> </div> <!-- /ko --> </div> <!-- ko foreach: getRegion('item_message') --> <!-- ko template: getTemplate() --><!-- /ko --> <!-- /ko -->
Now we will check how to display Cart items's original price on checkout/cart page in items table display.
For that, first we will modify app/code/Magelearn/Checkout/view/frontend/layout/checkout_item_price_renderers.xml file.
<?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="checkout.item.price.unit"> <action method="setTemplate"> <argument name="template" xsi:type="string">Magelearn_Checkout::item/price/unit.phtml</argument> </action> </referenceBlock> </body> </page>
Now as per defined in above layout file, we will copy file from vendor/magento/module-weee/view/frontend/templates/item/price/unit.phtml and paste it at app/code/Magelearn/Checkout/view/frontend/templates/item/price/unit.phtml
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ /** * @var $block \Magento\Weee\Block\Item\Price\Renderer * @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer */ /** @var \Magento\Weee\Helper\Data $weeeHelper */ $weeeHelper = $block->getData('weeeHelper'); $item = $block->getItem(); ?> <?php if ($block->displayPriceInclTax() || $block->displayBothPrices()): ?> <span class="price-including-tax" data-label="<?= $block->escapeHtmlAttr(__('Incl. Tax')) ?>"> <?php if ($block->displayPriceWithWeeeDetails()): ?> <span class="cart-tax-total" data-mage-init='{"taxToggle": {"itemTaxId" : "#unit-item-tax-details<?= (int) $item->getId() ?>"}}'> <?php else: ?> <span class="cart-price"> <?php endif; ?> <?= /* @noEscape */ $block->formatPrice($block->getUnitDisplayPriceInclTax()) ?> </span> <?php if ($weeeHelper->getApplied($item)): ?> <span class="cart-tax-info no-display" id="unit-item-tax-details<?= (int) $item->getId() ?>"> <?php foreach ($weeeHelper->getApplied($item) as $tax): ?> <span class="weee" data-label="<?= $block->escapeHtmlAttr($tax['title']) ?>"> <?= /* @noEscape */ $block->formatPrice($tax['amount_incl_tax'], true, true) ?> </span> <?php endforeach; ?> </span> <?php if ($block->displayFinalPrice()): ?> <span class="cart-tax-total" data-mage-init='{"taxToggle": {"itemTaxId" : "#unit-item-tax-details<?= (int) $item->getId() ?>"}}'> <span class="weee" data-label="<?= $block->escapeHtmlAttr(__('Total Incl. Tax')) ?>"> <?= /* @noEscape */ $block->formatPrice($block->getFinalUnitDisplayPriceInclTax()) ?> </span> </span> <?php endif; ?> <?php endif; ?> </span> <?php endif; ?> <?php if ($block->displayPriceExclTax() || $block->displayBothPrices()): ?> <span class="price-excluding-tax" data-label="<?= $block->escapeHtmlAttr(__('Excl. Tax')) ?>"> <?php if ($block->displayPriceWithWeeeDetails()): ?> <span class="cart-tax-total" data-mage-init='{"taxToggle": {"itemTaxId" : "#eunit-item-tax-details<?= (int) $item->getId() ?>"}}'> <?php else: ?> <span class="cart-price"> <?php endif; ?> <?php $price = $block->getUnitDisplayPriceExclTax(); $regular_price = $item->getProduct()->getPriceInfo()->getPrice('regular_price')->getAmount()->getValue(); ?> <?php if($price != $regular_price): ?> <?= /* @noEscape */ $block->formatPrice($block->getUnitDisplayPriceExclTax()) ?> <p class="old-price"><?= /* @noEscape */ $block->formatPrice($item->getProduct()->getPriceInfo()->getPrice('regular_price')->getAmount()->getValue())?></p> <?php else: ?> <?= /* @noEscape */ $block->formatPrice($block->getUnitDisplayPriceExclTax()) ?> <?php endif; ?> </span> <?php if ($weeeHelper->getApplied($item)): ?> <span class="cart-tax-info no-display" id="eunit-item-tax-details<?= (int) $item->getId() ?>"> <?php foreach ($weeeHelper->getApplied($item) as $tax): ?> <span class="weee" data-label="<?= $block->escapeHtmlAttr($tax['title']) ?>"> <?= /* @noEscape */ $block->formatPrice($tax['amount'], true, true) ?> </span> <?php endforeach; ?> </span> <?php if ($block->displayFinalPrice()): ?> <span class="cart-tax-total" data-mage-init='{"taxToggle": {"itemTaxId" : "#eunit-item-tax-details<?=(int)$item->getId()?>"}}'> <span class="weee" data-label="<?= $block->escapeHtmlAttr(__('Total')) ?>"> <?= /* @noEscape */ $block->formatPrice($block->getFinalUnitDisplayPriceExclTax()) ?> </span> </span> <?php endif; ?> <?php endif; ?> </span> <?php endif; ?>
At last, we will add our CSS file at app/code/Magelearn/Checkout/view/frontend/web/css/source/_module.less to display data properly.
2 Comments On "Magento2 Display Old Price, Discount Percentage and Saved Amount to Minicart to Checkout Cart Products"
Thanks for your tutorial
How display products total discount amount in Minicart
like this : https://prnt.sc/22u8hsm
Hello Shajuss,
From This post you can develop your custom logic and complete your task as per your requirement.
I will moddify this post in few days and cover your requirement.
Till then if you have any query in this post then let me know.