How to Create Custom Magento 2 Widgets
Widgets play a pivotal role in Magento development, as they’re often used to display targeted content and provide crucial front-end functionality. Magento 2 offers a lot of widget possibilities out of the box, and also allows developers to unlock more features using custom widgets.
In this article, Toptal Freelance Software Engineer Vivek Khatri provides an overview of widget implementation in Magento 2, starting with the basics and culminating in custom widget design.
Widgets play a pivotal role in Magento development, as they’re often used to display targeted content and provide crucial front-end functionality. Magento 2 offers a lot of widget possibilities out of the box, and also allows developers to unlock more features using custom widgets.
In this article, Toptal Freelance Software Engineer Vivek Khatri provides an overview of widget implementation in Magento 2, starting with the basics and culminating in custom widget design.
Vivek Khatri
Vivek is a Magento certified developer with over 6 years of experience. He focuses on the business needs of clients when creating solutions.
Widgets allow Magento 2 store administrators to add static/dynamic content to CMS pages and blocks, providing a lot of functionality and straightforward implementation. Widgets are reusable components that can be added in any CMS block of Magento 2.
Hence, they allow Magento 2 developers and store administrators to add interactive interfaces and features in the front-end without having to know much about programming. Of course, they still need to know their way around Magento to create a widget.
The goal of this article is to demonstrate how to create widgets in Magento 2, with an emphasis on custom widgets.
Magento 2 Widgets
Magento 2 is the latest version of Magento, one of the leading eCommerce platforms today. Widgets play an important role in Magento 2, especially from a functionality standpoint. In addition to offering more user-side functionality, Magento widgets help administrators add static or dynamic content to CMS pages and blocks.
But, from a technical perspective…What’s a Magento widget?
A Magento 2 widget is essentially a Magento extension designed with a set of advanced configuration options. Due to greater flexibility and control, they are used to provide information and marketing content via the Magento Administrator panel. One of the advantages of Magento 2 widgets is that you can “call” them from anywhere on the site.
Widgets also allow administrators to add interactive interfaces and features in the Magento front-end, without having to code (actually, without even knowing how to code).
Magento 2 Offers Multiple Types of Widgets
Before we move on to implementation, let’s take a closer look at the standard range of widgets supported in Magento 2:
- Recently Compared Products — You must have observed this widget while browsing products on your favorite e-commerce sites. This widget is used to display recently viewed or compared products in the sidebar of a catalog page. They may also appear in your store depending on the theme. One of the crucial points is that the number of products which are listed in every single block can be configured.
- Orders and Returns — Whenever you shop for a product online, there is a must-have widget that provides quick access to orders and returns. If a user wants to review ordered or returned products, they can fill in the necessary details such as Order ID, Billing the Last Date, Find Order by, Email, etc.
- Catalog Products List — This is another widely used widget; everyone is familiar with the “featured product” sections on eCommerce sites, as almost every site has one. Featured products are usually placed on the home page for the purpose of product promotion. The particular product is shown with brief details like price, features, and options like add to cart, add to wishlist, and add to a comparison feature.
- Catalog Product Link — The main purpose of the Catalog Product Link widget is that it allows admins to manage links for products, including related products, cross sells, upsells, and grouped products. When you visit the catalog product link page, you will see different catalog categories initiated with an introduction. There, you’ll find catalog product links with various sub-links, such as catalog product link assign, catalog product link attributes, catalog product link removes, catalog product link types, and more.
- Catalog Category Link — In eCommerce websites, especially product-based ones, you will find no shortage of catalog category link widgets.
- Custom Block Widget — It’s possible to combine blocks, widgets and custom pages to display parts of the catalog or other information customers may find useful.
These can be used to improve the user experience and add functionality to the store. Blocks and widgets are important elements of most eCommerce websites. They allow users to quickly generate and control content, and can be used to do things like:
- Add dynamic/informational blocks in sidebars
- Add banners in CMS pages
- Add custom menus
- Add interactive user interfaces
The Case for Magento 2 Custom Widgets
Any website or web page needs a lot of functionality to run smoothly and to engage more visitors, and creating an engaging user experience is a must in eCommerce. That’s where custom Magento 2 widgets come into play, and that’s what they’re supposed to do.
Widgets are smaller sets of code that we can add to the store. Using simple links to dynamic code, widgets can display all sorts of useful data tailored to help visitors and improve their experience. The ability to boost engagement using low-overhead, reusable widgets obviously means a lot, but sometimes it’s not just a matter of choosing and adding an off-the-shelf widget.
Using the Custom Widget functionality in Magento 2 allows us to create our own widget templates. A custom widget can sometimes offer an even better way of editing or adding quality content inside CMS blocks or pages.
However, before we move on to custom widgets, we need to examine a standard use case for widgets in Magento 2. Let’s take a look at something basic and widely used, for example:
How to Add a New Product List to the Homepage Using a Widget
This simple widget allows us to add a new product list wherever required on the website, and there are various ways by which new products can be listed in Magento 2.
To add a Magento product list to the home page, you merely need to follow a simple process:
- Log in to the Magento 2 admin page and go to Content > Widget
-
Click on the Add Widget button. After that, we’ll be redirected to the Settings tab, where we have to select Type and Design options and themes.
-
We can see the screenshot below, in which we have already selected the Catalog New Product List that we’ll be displaying at the front-end.
- We selected LUMA as the Design Theme option.
- After selecting both values, we have to move on the second step, where we have to fill storefront properties. Now we have to set the Widget Title and Storefront Properties, such as Widget Title and Store View. We are using Toptal New Product List and All Store Views.
- The most important part is the Layout Updates section, which will tell us where this widget is going to appear (e.g., home page, listing page, checkout page, etc.). It’s also possible to define an area in which the container will appear—for example, below header, above footer, footer, etc.
Layout Updates settings provide you with the following options:
- Display On: Specified Page or All pages.
- Page: CMS Home Page
- Container: Main Content Area
- Template: Here, you can select in which style you would like to display new products Grid mode or List mode
Once we select the Specified Page option, we can proceed to set the properties, allowing us to display the widget on a particular page. Here we have the Page dropdown, which allows us to select CMS Home Page. Next, we need to select the container and template we are going to use to display the widget at a particular section.
Finally, we move to the last tab, which includes widget options. Here, we can set the Condition, such as what type of products are going to be displayed, or include limits to the number of products and so on.
If we select All Products, then the most recently added product will be displayed in this section. If we select New Products, then only those products that we marked as “New” will be displayed in this section. If we want to let our customers control navigation for multiple lists, we need to set the Display Page Control to “Yes.” If we have selected “Yes,” then it’s necessary to enter the number of products into the list.
In Number of Products to Display, we can define how many products can be displayed in the New Products section. Also, we can change Cache Lifetime settings if necessary.
Now we have to save this widget and flush the Magento 2 cache. This can be done from admin or the command line. We can use the following command to flush the cache:
php bin/magento cache:clean and php bin/magento cache:flush
Then we will be able to see the new products on the home page.
How to Create a Custom Widget in Magento 2
Now, we’ll learn how to create custom widgets for Magento 2. Custom widgets offer the best way of adding and editing content inside CMS blocks or pages, because they can be tailored to match your requirements.
Let’s start with the basics. We all know how to create a module, right? Just in case you’re not familiar with the creation of custom modules in Magento 2, we have a great tutorial that covers the process in-depth.
Now, let’s move on to the step-by-step process of creating custom widgets in Magento 2.
First, we need to create a new module which will requires namespace and module folders. For this example, we are going to use Toptal
for namespace and CustomWidget
for the module name. So, let’s start as usual with composer.json
, registration.php
, and etc/module.xml
.
app/code/Toptal/CustomWidget/composer.json
This file will be loaded by Composer every time we run it, even though we are not actually using Composer with our module.
Now we need to register our module with Magento, so we are required to create the register.php
at the following location: app/code/Toptal/CustomWidget/registration.php
.
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Toptal_CustomWidget',
__DIR__
);
Now, we will create the last registration file, module.xml
.
app/code/Toptal/CustomWidget/etc/module.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="Toptal_CustomWidget" setup_version="1.0.0"/>
</config>
After completing the registration step, next we create the widget.xml
configuration file.
app/code/Toptal/CustomWidget/etc/widget.xml
<?xml version="1.0" ?>
<widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Widget:etc/widget.xsd">
<widget class="Toptal\CustomWidget\Block\Widget\Samplewidget" id="toptal_customwidget_samplewidget">
<label>Toptal Sample Widget</label>
<description></description>
<parameters>
<parameter name="widgettitle" sort_order="10" visible="true" xsi:type="text">
<label>Title</label>
</parameter>
<parameter name="widgetcontent" sort_order="20" visible="true" xsi:type="textarea">
<label>Content</label>
</parameter>
</parameters>
</widget>
</widgets>
In the above code, we get Title
and Content
as parameters to be displayed wherever the widget is called. The <widget>
tag contains the block class Toptal\CustomWidget\Block\Widget\Samplewidget
. This class is decelerated within Block/Widget/Samplewidget.php
. The class instructs our widgets on which template to use.
The next snippet of code shows how to define a block for the widget; we’ll set our template here. Let’s see how it looks.
app/code/Toptal/CustomWidget/Block/Widget/Samplewidget.php
<?php
namespace Toptal\CustomWidget\Block\Widget;
use Magento\Framework\View\Element\Template;
use Magento\Widget\Block\BlockInterface;
class Samplewidget extends Template implements BlockInterface
{
protected $_template = "widget/samplewidget.phtml";
}
Toptal\CustomWidget\Block\Widge\Samplewidget
is declared above code. In this file, we assign a custom template file inside the $_template
variable.
Next, we’ll see what contains our widget template.
app/code/Toptal/CustomWidget/Block/view/frontend/templates/widget/samplewidget.phtml
<?php if($block->getData('widgettitle')): ?>
<h2 class='toptal-title'><?php echo $block->getData('widgettitle'); ?></h2>
<?php endif; ?>
<?php if($block->getData('widgetcontent')): ?>
<h2 class='toptal-content'><?php echo $block->getData('widgetcontent'); ?></h2>
<?php endif; ?>
Here, we can see how to pick up the value from widget parameters. It’s simple:
$this->getData(‘widgettitle’);
and
$this->getData(‘widgetcontent’);
What is our end-result? Let me show you what it looks like in Magento Admin:
Now we have to save this widget and flush the cache. As outlined previously, this can be done from admin or the command line, using php bin/magento cache:clean
and php bin/magento cache:flush
You can download this simple module here. It’s obviously not a full Magento 2 widget template, but it’s still a learning aid. In case you need more resources, or if you’re relatively new to Magento, official Magento 2 documentation is the obvious place to start.
Finally, I’d like to mention a couple of personal dev blogs I found quite useful. Alan Storm has probably the most didactic content when it comes to learning Magento, and I think you should check out Alan Kent’s blog as well.
Widgets: A Crucial Part of the Big Picture
The goal of this article was to provide a guide to widget creation in Magento 2, starting with a basic step-by-step tutorial covering Magento 2 widget development and custom widget creation. I am obviously a fan of the latter, as custom solutions tend to provide more flexibility and functionality.
Magento widgets provide crucial front-end functionality, so it’s no stretch to say that clever custom widgets can help bring your next Magento project to the next level. The allow us to to implement even more functionality, add different types of items to the home page using different widgets, and ultimately, they simply provide developers with more creative freedom.
But it’s not just a matter of improving user experience and conversions, or making an awesome looking design. All are obviously a priority for any client, but there are smaller, less obvious gains. For example, Magento widgets can save a lot of time and headaches on the admin side as well, and every client is looking to save man-hours as well.
However, that’s beyond the scope of this article. My intent was to provide a quick technical overview, an easy to follow Magento 2 widget tutorial, not to discuss ROI and marketing.