How to Use Total Models in Magento 2

Oct 30, 2018206Gennadiy Haritonov
How to Use Total Models in Magento 2

Custom totals help you modify the calculation process in the shopping cart. They can be used to add an extra tax or discount to Magento Checkout or modify the existing ones and they are later applied to the products in the shopping cart. BTW, this topic is included into the Magento 2 professional developer certification exam.

Adding Custom Total

The first thing we need to do is create an app/code/Vendor/Module/etc/sales.xml file in our module. This file is used to register all the available totals in Magento 2.

app/code/Vendor/Module/etc/sales.xml:

Here we specified the \Vendor\Module\Model\Totals\Custom class as a model of our custom total. This class must inherit \Magento\Quote\Model\Quote\Address\Total\AbstractTotal and also implement the collect and fetch methods. The collect method is used to calculate the value of our total, and the fetch method returns this value, as well as the total’s code and its name.

The \Magento\Quote\Model\Quote\Address\Total $total parameter also allows you to affect the result of the other total classes. But depending on the task, it may make more sense to use plugins to modify their values.

app/code/Vendor/Module/Model/Total/Custom.php:

Displaying Custom Total

Cart and checkout pages

Knockout.js is used for displaying totals. In order for our total to appear on the cart and checkout pages, we need to add a new js component to checkout_cart_index.xml and checkout_index_index.xml layouts.

app/code/Vendor/Module/view/frontend/layout/checkout_cart_index.xml:

app/code/Vendor/Module/view/frontend/layout/checkout_index_index.xml

And also write the components and HTML templates:

app/code/Vendor/Module/view/frontend/web/js/view/checkout/cart/totals/custom_total.js

app/code/Vendor/Module/view/frontend/web/template/checkout/cart/totals/custom_total.html

app/code/Vendor/Module/view/frontend/web/js/view/checkout/summary/custom_total.js

The getValue and getPureValue methods return the value of our custom total, but the getValue method formats this value by adding two decimal digits and a symbol of the current currency.

app/code/Vendor_Module/view/frontend/web/template/checkout/summary/custom_total.html

Order Emails

To make a new total display in the order email you need to add a new block in the sales_email_order_items layout.

app/code/Vendor/Module/view/frontend/layout/sales_email_order_items.xml

app/code/Vendor/Module/Block/Order/CustomTotal.php

That is it, thank you for reading. Leave your comments and questions below and good luck at the exam!



Post a new comment

top
BelVG Newsletter
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
Email *