Magento 2 widgets

Magento 2 widgets DEFAULT

Magento 2 custom widget

In one of our previous articles we learned how to create a widget. Now we will see how we can create a custom one, or even better, how to extend the core one. For this example I picked default catalog product listing widget that I will extend with sorting fields for better customization of this widget.

Module setup

First we need to create a new module. This requires namespace and module folders with and inside module folder. For this example I am going to use Inchoo for namespace and CatalogWidget for module name. If you are unfamiliar with development preparations and creation of custom modules in magento 2, we have a great article to get you started.

registration.php

etc/module.xml

Custom code

First we will create widget configuration which is almost identical to one used in extended widget. We do this by creating file in etc folder. Apart from label and description nodes changes, there are two extra parameters and that we will later use to sort our product collection. Parameter type is select, and they are using our custom source models we will create in the following steps. Other differences are container nodes that I will explain later on, and options for template parameter. I added our own template option with name . This will be our own custom template to render products list just how we want to. Last but not least important is custom widget placeholder image. We will place it at .

etc/widget.xml

We have two custom parameters with two custom source models. I like to organize my modules just like core magento, so I will create models at .

Model/Config/Source/SortBy.php

Model/Config/Source/SortOrder.php

Next step is to create a custom block that our widget will use.To make things easier we will extend block from . This will give us all existing features of catalog product listing widget that Magento prepared for us.
We are overriding method from to add sorting order on collection. I added “collection_sort_by” and “collection_sort_order” attribute getters with fallback on default values that are defined at the start of the class. This custom parameters are defined in configuration.

Code is ready, it’s time for testing.picking_widget

Containers

While creating widgets we have layout update options where we can specify on which page and in which container will our widget be rendered at. To show its full potential I will create our custom template file. For this example I copied the normal product listing template. Again, trying to keep the consistency, I am mimicking the path of template creation to . In our widget configuration we specified two containers, one named content, and the other one named content.top. In the first one I defined two templates, grid and top-products. Values of this nodes will show template options with same names. This gives us ability to allow certain custom templates to be available for rendering in only certain containers.

Main Content Area – , template select is available.
layout_updates_1
Main Content Top – , template select is not available.
layout_updates_2edited
Source available on github.

Sours: https://inchoo.net/magento-2/magento-2-custom-widget/

Widgets provide powerful features in Magento 2, that are used to add dynamic or static content to store’s pages. Here are the widgets that are available by default:

  • CMS Page Link
  • CMS Static Block
  • Catalog Category Link
  • Catalog New Products List
  • Catalog Product Link
  • Catalog Products List
  • Orders and Returns
  • Recently Compared Products
  • Recently Viewed Products

Configuration options

OptionDescriptionTypeRequired
The name of the widgetString
Contains a concise explanation of the widget’s purposeString
A list of widget’s optionsObject
A list of layout containers, where the widget may be injectedObject

This tutorial shows you how to create and insert your own widget on the frontend.

Step 1. Declaring the widget

We need to also add a dependency to Magento_Widget in the file.

Step 2. Adding widget parameters

As a parameter, we are able to use any of these field types:

  • text
  • select
  • multiselect
  • block

Add a text and a select field:

Step 3. Check the widget

Run the following commands to apply the module dependency declared in .

where is replaced with the module name.

After clearing the cache, the new widget should be available.

Custom Widget

To add it to the homepage, below the page content:

After selecting the widget type and the layout location, we should be able to see the widget’s options.

Widget Options

Step 4. Create the block

Create the block class that we provided on the widget’s initialization, responsible for rendering it on the frontend.

Step 5. Create the template

And finally, create the template that will be used for showing the widget’s data on the frontend.

Step 6. Clean Cache

Clean the Magento cache with the following command:

Result

The widget is now shown on the frontend.

Widget Options

Sours: https://devdocs.magento.com/guides/v2.4/ext-best-practices/tutorials/custom-widget.html
  1. Flyrig 5 review
  2. Herbal clean how to video
  3. Toyota camry 2012 xle review

How to add custom widgets to Magento 2?

What is the Magento 2 widget?

Magento 2 widget is a snippet of code that allows you to display dynamic content on your store frontend. You can use it to involve visitors and create opportunities to interact with your store. Widgets allow you to place different content like images, text, or static blocks at any place in your store.

Setting up widgets in Magento is a complex process that requires some work with code. Here is a step-by-step guide for setting up custom widgets in Magento.

Warning: all code snippets in this article are examples. You need to customize them to suit your business needs.

How to add Magento 2 widget parameters?

Magento 2 widget parameters that you can use are text, select, multi-select, and block. Say, you need to add the text and select fields to your Magento 2 custom widget. For this, you can use the following code:

Step 1. The first step is to declare the widget.

The code below must be inserted into the etc/widget.xml file:

<widgetsxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Widget:etc/widget.xsd">    <widgetclass="OrangeCompany\Learning\Block\Widget\Test"id="orange_test_widget">        <label>My New Widget</label>        <description>This is a test widget!!!</description>        <parameters>            ...        </parameters>        <containers>            ...        </containers>    </widget></widgets>

In addition, we need to create a dependency on Magento_Widget in the module.xml file.

To do this, open the etc / module.xml file and paste the following code:

...<sequence>    <modulename="Magento_Widget"/></sequence>...

Step 2. The next step is to add widget parameters.

There are some field parameters you can use:

  • text
  • select
  • multiselect
  • block.

Say, you need to add the text and select fields. Use the following code:

<widgetsxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Widget:etc/widget.xsd">    <widgetclass="OrangeCompany\Learning\Block\Widget\Test"id="orange_test_widget">        ...        <parameters>            <parametername="title"xsi:type="text"required="true"visible="true"sort_order="10">                <label>Label</label>            </parameter>            <parametername="size"xsi:type="select"visible="true"required="true"sort_order="20">                <labeltranslate="true">Size</label>                <options>                    <optionname="s"value="S">                        <label>S</label>                    </option>                    <optionname="m"value="M"selected="true">                        <label>M</label>                    </option>                    <optionname="l"value="L">                        <label>L</label>                    </option>                </options>            </parameter>        </parameters>    </widget></widgets>

Step 3. On this step, you need to check the widget.

To do this, run the following commands:

bin/magento module:disable Vendor_Module

bin/magento module:enable Vendor_Module

Replace Vendor_Module with the module name.

These commands allow you to apply the module dependency declared in the module.xml file. Then clear the cache, and a new widget will be available for selection:

custom widget

When the widget type and layout location are selected, you will see the options of the widget:

custom widget settings

Step 4. Now we need to create the block class provided on the widget’s initialization, which is responsible for rendering it on the frontend page.

Open OrangeCompany/Learning/Block/Widget/Test and use the following code:

namespaceOrangeCompany\Learning\Block\Widget;useMagento\Framework\View\Element\Template;useMagento\Widget\Block\BlockInterface;classTestextendsTemplateimplementsBlockInterface{    protected$_template="widget/test.phtml";}

Step 5.  Now you need to create the Magento 2 widget template.

This Magento widget template will be used to show the data of the widget on the frontend page.

In the OrangeCompany / Learning / view / frontend / templates / widget / test.phtml file, use this code:

<?php/** \OrangeCompany\Learning\Block\Widget\Test $block */?><h3><?=$block->escapeHtml($block->getData('title'))?></h3><h3><?=$block->escapeHtml(__('Size:'))?><?=$block->escapeHtml($block->getData('size'))?></h3>

Step 6. The last step is to clean the cash.

Use bin/magento cache:clean command to clean the cash.

That's it. Now your Magento 2 widget will be shown on the frontend page.

For more information, check the official Magento documentation.

How to create a Magento 2 widget programmatically?

To create a Magento 2 widget programmatically, you need to declare the widget, create a dependency, add widget parameters, and create the frontend template. How to create a custom widget in Magento 2 step-by-step with code samples you can find below in the article.

Using widgets on your storefront can increase user engagement. For example, our Blog Pro extension can add widgets with categories, recent posts, and comments to your blog page. As a result, highlighted articles will get more attention.

Sours: https://amasty.com/knowledge-base/how-to-add-custom-widgets-to-magento-2.html
How to Display CMS Blocks on Magento 2 Pages using Widgets?

How to Create a Custom Widget in Magento 2

Widget is a greater tool to insert or edit content into a CMS Page Block or Page, so I am so happy to bring you Create Widget in Magento 2 topic. Reading the post will help you understand: “What are the widgets in Magento 2?” and “How to use them on Magento 2 store”. With this simple instruction, it is easy to create and customize new custom widgets in Magento 2.

Table contents

What is the widget in Magento 2?

Firstly, we all will get to know the definition of Widget in Magento 2.

Widgets are the powerful functionalities in Magento 2 configuration. As a store admin, you can take the advantage of the widget to improve the storefront under the lively interface. The widgets allow showing static information or dynamic content to CMS pages or blocks. You can add widgets in any CMS block of Magento 2 to display such content or elements, for example:

  • Dynamic product data
  • Dynamic lists of the recently viewed products
  • Promotional banners
  • Interactive navigation elements and action blocks
  • Dynamic flash elements that are inserted in content pages

The customization of the widgets in Magento 2 is similar to an optimized front-end extension with a simple module. It’s hassle-free to create a Magento 2 widget because it is the same as when you create a HelloWorld excepting from some additional files. Hence, although you don’t have any experience in programming, it is easy to improve your storefront with the dynamic blocks of content.

Here are available default widgets:

  • CMS Static Block
  • CMS Page Link
  • Recently Compared Products
  • Recently Viewed Products
  • Catalog Products List
  • Catalog Product Link
  • Catalog New Products List
  • Catalog Category Link

With this guide below, you can create your own widget in Magento 2 easily and quickly.

4 steps to creating a widget in Magento 2

  • Step 1: Declare widget
  • Step 2: Create a widget template file
  • Step 3: Create widget Block class
  • Step 4: Flush cache and posts

Step 1: Declare widget

Create a file with the following content

Step 2: Create a widget template file in Magento 2

File:

Step 3: Create widget Block class

Create block file:

Step 4: Flush cache and posts

Go to

In tab, click on icon

Magento 2 insert widget

You will see the in widget list

magento 2 widgets

Conclusion

Though it requires no high level of programming for the store admins to add features and interactive content to the website by widgets, they still need to understand how it works in Magento 2 to create a widget. This guide gets you through the process of utilizing widgets from the functionality standpoint to streamline your Magento 2 store. If you have any questions, let us know in the comment section. Thanks for reading.

Related Post

One Step Checkout for Magento 2 by Mageplaza

magento-2-tutorial

create

widget

featured

Sam Thomas
Sam Thomas

CEO and Founder of Mageplaza. Pursueing a simple and healthy lifestyle. A friend, a husband and a dad of two children, a trainer and an influencer wannabe. He is a big fan of sports and travel, also.

People also searched for

  • magento 2 widget
  • magento 2 create widget
  • magento 2 create widget programmatically
  • magento 2 custom widget
  • magento 2 create custom widget
  • create widget magento 2
  • widget magento 2
  • how to create widget in magento 2
  • magento2 widget
  • create widget in magento 2
  • magento 2 add widget programmatically
  • magento 2 widget tutorial
  • magento 2 widget parameters
  • magento 2 custom widget product list
  • magento 2 widget.xml
  • widgets magento 2
  • magento 2 widget template
  • devdocs magento2
  • magento widgets
  • 2.2.x, 2.3.x, 2.4.x
Sours: https://www.mageplaza.com/devdocs/magento-2-create-widget/

2 widgets magento

Widgets are reusable components and you can easily create new widgets, as well as modify existing ones to automatically update content across your store. You can also delete widgets that are no longer in use.

Widgets

Create a widget

The process of creating a widget is nearly the same for each widget type. You can follow the first part of the instructions, and then complete the last part for the specific type of widget you want.

Step 1: Choose the type

  1. On the Admin sidebar, go to Content > Elements > Widgets.

  2. Click Add Widget.

  3. In the Settings section:

    • Set Type to the widget type that you want to create.

    • Verify that Design Theme is set to the current theme.

    Widget settings

  4. Click Continue.

Step 2: Specify storefront properties and layout

  1. In the Storefront Properties section:

    • For Widget Title, enter a descriptive title for the widget.

      This title is visible only from the Admin.

    • For Assign to Store Views, select the store views where the widget will be visible.

      You can select a specific store view, or . To select multiple views, hold down the Ctrl key (PC) or the Command key (Mac) and click each option.

    • (Optional) For Sort Order, enter a number to determine the order this item appears with others in the same part of the page. ( = first, = second, = third, and so on.)

    Storefront properties

  2. In the Layout Updates section, click Add Layout Update.

  3. Set Display On to the type of page where it is to appear.

  4. In the Container list, choose the area of the page layout where it is to be placed.

    Layout updates

  5. If the widget is a link, set Template to one of the following:

    Block TemplateFormats the content so it can be placed as standalone unit on the page.
    Inline TemplateFormats the content so it can be placed inside other content. For example, a link that goes inside a paragraph of text.

Step 3: Complete the widget options

The options for each widget type vary slightly, but the process is essentially the same. The following example displays the product list for a specific category, with pagination controls.

  1. In the left panel, choose Widget Options.

  2. Click Select Block.

  3. Enter a Title to appear above the list, such as .

  4. For pagination controls, set Display Page Control to and do the following:

    • Enter the Number of Products per Page.

    • Enter the total Number of Products to Display.

    • Set Condition to the category of products to be featured.

      The process is the same as setting a condition for a price rule.

    Widget options

Step 4: Save and check the result

  1. When complete, click Save.

  2. When prompted, follow the instructions at the top of the workspace to update the cache, as needed.

  3. Return to your storefront to verify that the widget is working correctly.

    To move it to a different location, you can reopen the widget and try a different page or block reference.

Edit a widget

  1. On the Admin sidebar, go to Content > Elements > Widgets.

  2. Locate the widget using filters above the grid and click the widget name.

  3. Make needed changes.

    Review the steps for creating a widget for information about the widget options.

  4. Click the Save.

Delete a widget

  1. On the Admin sidebar, go to Content > Elements > Widgets.

  2. Locate the widget using filters above the grid, select the checkbox of the widgets to be deleted.

  3. In the upper-left corner of the list, set Actions to .

  4. When complete, click Submit.

  5. To confirm the action, click OK.

Sours: https://docs.magento.com/user-guide/cms/widget-create.html
Magento - Add new Widget

Blocks and Widgets are the key layout features in Magento. These two features are very closely linked, and are often used together.

One way to think about Blocks is that they are mini-Pages. A Block can also contain text, images, video and more. But because Blocks are smaller, you will see them around the edges of your site. Blocks are often inserted into headers, sidebars and footers.

However, Blocks are placed using Widgets. First you create a Block, and then you use a Widget to decide where that Block will be displayed.

Let's walk you through some examples and show you how Blocks and Widgets work in Magento.

This guide is taken from Magento 2 Explained, the best-selling book for Magento 2. We use the example of a store called "Orangeville" in that book, so you'll see it referred to here.


Creating Magento Blocks Explained

Let's go through the process of creating our first Block. This will contain an HTML link.

  • Go to "Content", and then "Blocks".
  • Click "Add New Block" in the top-right corner.

add new magento block

  • Enter "Key Links" as the "Block Title". This is what visitors will see on the screen.
  • Enter "key_links" as the Identifier. This string is what Magento uses to identify the block, but visitors will never see it.

key links magento block

  • Click the bullet icon in the editor toolbar:

editing magento block

  • Type "About Orangeville" as a bullet point:
  • Select the "About Orangeville" text and click the link icon.

link inside magento block

  • You will now see a pop-up window. Enter the URL of your "About Orangeville" page. If you're not sure what this is, you can open your Magento site in a new browser tab and find the URL, which is likely to be example.com/about-orangeville/.
  • Click "Insert".
  • You now have an "About Orangeville" link inside your Block:

about orangeville


Creating Magento Widgets Explained

We now have the challenge of placing your block into your site design. This is where Magento's Widgets come in useful. In Magento, a Block is just a piece of content. It's the Widget that controls the placement of the Block.

However, that's not all a Widget can do. A Widget can place our simple, new Blocks, but it can also place many other features.

  • Go to "Content", and then "Widgets".
  • Click "Add Widget".
  • For "Type", choose "CMS Static Block".
  • For "Design Theme", choose "Magento Luma".
  • Click "Continue".

create magent block

  • Enter "Key Orangeville Links" for the "Widget Title".
  • Under "Assign to Store Views", select "All Store Views".

key links magento block

Next, we're going to control which URLs this Block appears on.

  • Click "Add Layout Update".

magento layout updates

magento all pages layout

  • Choose "CMS Footer Links" for the "Container" option.

magento cms footer

Both of these choices, "All Pages" and "CMS Footer Links", may not make much sense to you yet. However, we'll finish creating the widget and later in the chapter, in the section called, "Magento Widget Placement Explained", we'll explain more about why we made these choices.

Under "Layout Updates", we're going to make a second choice for where to place our widget.

  • Choose "All Product Types".
  • Choose "CMS Footer Links" again.
  • After adding both of these options, your screen will look like the image below.

magento block placement

At this point, you've created the Widget and told Magento where it should appear on your site: this Widget will appear on all our Pages and all our Products.

Now it's time to choose the content of the Widget, which will be the Block you created earlier.

  • Click "Widget Options" in the sidebar.
  • Click "Select Block".

select magento block

  • Now you can choose the "Key links" block you created earlier:

select magento block

  • Click "Save".
  • Visit the front of your site, and you'll see your link is now published in the footer. You created a Block with the content, and published it inside a Widget.

new magento block visible


Creating Blocks and Widgets Together

There are definitely some tricky steps as you create Blocks and Widgets. So let's try this whole process together. We'll create a second Block and place it on our site with the help of a Widget. This Block will tell people that we have a 100% satisfaction guarantee.

  • Go to "Content", and then "Blocks".
  • Click "Add New Block".
  • Title: Satisfaction Guaranteed
  • Identifier: guarantee

new magento block

  • Enter text for your Block. I wrote "Here at Orangeville, your satisfaction is our top priority. If you're not happy, we'll refund your money."

new image block magento

Next, we're going to upload an image for our block. 

  • Place your cursor into the main content area, below the text that you just wrote.
  • Click the tree icon in your editor toolbar.
  • When you see the pop-up box, click the small box icon.
  • Find an image that you can upload. I've choosen a 100% badge.

add image magento block

  • Click "Insert File".
  • Image Description: Satisfaction Guarantee 
  • Click "Insert".

uploading magento image

  • You now have a Block that contains both text and your new image.
  • Click "Save Block" to finish creating this Block.

new magento block with image

Next, let's create the Widget that will display this Block on our site.

  • Go to "Content", and then "Widgets".
  • Click "Add Widget".
  • Type: CMS Static Block
  • Design Theme: Magento Luma

magento block settings

  • Widget Title: Satisfaction Guaranteed
  • Assign to Store Views: All Store Views

magento block properties

  • Layout Update: Anchor Categories
  • Container: Sidebar Main
  • Click "Widget Options" and choose the "Satisfaction Guaranteed" Block that you just created.

magento widget options choose

  • Click "Save".
  • Visit the front of your site. Click on one of the category links in the top menu. In the image below, I clicked on "Fruit". You will now see your guarantee Block in the left sidebar:

magento block in sidebar


Magento Widget Placement Explained

One common question I get from Magento  learners is about the placement of Widgets.

How do you know to choose "CMS Footer Links" or "Sidebar Main" for the Container? After all, there are 22 different choices, as you can see in the image below.

What's the difference between "After Page Header" and "After Page Header Top"? What's the difference between "Page Footer" and "Page Footer Container"? Those names are so similar that they can definitely be confusing.

magento widget containers

Unfortunately, there's no sure way to tell in advance, although the name will give you a good idea of the placement:

  • After Page Header: This is likely to be under the main menu.
  • Main Content Bottom: This is probably low down on central part of the screen, underneath our products or Page content.
  • Page Top: This will appear high up on Pages, but not on Product screens.

It's worth noting that these options change, even on the same site. If you are trying to place a Block and choose "All Product Types" for your Widget's "Layout Options", then you will get a different set of choices, shown in the image below. These options provide some placements that only make sense for your product screens. For example, you now see choices that include "Product social links container" and "Review Form Fields Before". Those Widget placements don't make sense anywhere except for on Product screens.

On the other hand, this list can sometimes be much shorter. In the next part of this chapter, we'll see that some Widgets only come with three Container options.

So, there's no guaranteed way to tell exactly where your Widget will appear if you choose a particular Container. There will be some testing and experimentation involved as you test these different options.

magento widget container product


Magento Blocks and Widgets Summary

Blocks and Widgets allow you to add new items to your site's design. However, there are some elements on your site that can't easily be modified or replaced from Magento's admin interface. They look like they should be Blocks and Widgets, but Magento has not created them that way. So, I created a page with instructions for updating some of those default elements.

If you're ready to learn more about Magento, check out Magento 2 Explained, the best-selling book for Magento 2.

We also have some more great Magento tutorials online, including:


About the author

Steve is the founder of OSTraining. Originally from the UK, he now lives in Sarasota in the USA. Steve's work straddles the line between teaching and web development.


Sours: https://www.ostraining.com/blog/magento/blocks-widgets/

Now discussing:

Here’s How You Can Create a Custom Widget in Magento 2

Widgets are used to add static or dynamic content to the CMS pages and blocks in Magento 2. They are reusable elements providing different functionalities that can be added in any CMS block of Magento 2 store. Widgets are essential because they help visitors to view and surf your Magento 2 store with ease. It plays an important part in creating beautiful designs and templates in Magento 2, providing better user experience.

From the technical side, a widget is a Magento 2 module, which is designed with a set of advanced configuration options. Thanks to the great flexibility and control, widgets provide information and content directly using the Magento admin panel. The best part is that you can call a widget from anywhere on the Magento 2 store.

In this article, I will demonstrate how to create a custom widget in Magento 2 and use it on the homepage of the store. You can also create widget templates as per your desire.

Scale Your Magento 2 Store With Ease

One-Click Magento installation with your own managed hosting solution.

Start Now

So, let’s start with the basics. I think we all know how to create a module in Magento 2, right? In case you’re not familiar with it, here’s the link to an excellent tutorial that covers the simple process of creating a module in Magento 2 in-depth.

Now, let’s move on to the step-by-step process of creating a custom widget in Magento 2. First, create a new module using Cloudways as namespace and CustomWidget as the module name and create registration.php at Magento2_Root/app/code/Cloudways/CustomWidget/ directory.

<?php \Magento\Framework\Component\ComponentRegistrar::register(     \Magento\Framework\Component\ComponentRegistrar::MODULE,     'Cloudways_CustomWidget',     __DIR__ );

Cloudways Magento Hosting For Developers

Now, create a module.xml at Cloudways/CustomWidget/etc/ and add the following code.

<?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="Cloudways_CustomWidget" setup_version="1.0.0"/> </config>

Next, you’ll need to create a widget.xml configuration file at Cloudways/CustomWidget/etc/ with the following code.

<?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="Cloudways\CustomWidget\Block\Widget\Samplewidget" id="cloudways_customwidget_samplewidget">                         <label>Cloudways 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 abovementioned code, I have declared two input fields with labels Title and Content. Whatever the widget is called, it will display the value of both the fields. In the <widget> tag, I have declared a block class, Cloudways\CustomWidget\Block\Widget\Samplewidget that instructs our widget to use the particular template.

Now, I am going to create a block file named Samplewidget.php in Cloudways/CustomWidget/Block/Widget/ directory with the following code.

<?php namespace Cloudways\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"; }

In the above code, I have assigned a template file inside the $_template variable. Now, create a widget template file samplewidget.phtml in Cloudways/CustomWidget/view/frontend/templates/widget with the following code.

<?php if($block->getData('widgettitle')): ?>             <h2 class='cloudways-title'><?php echo $block->getData('widgettitle'); ?></h2> <?php endif; ?> <?php if($block->getData('widgetcontent')): ?>             <h2 class='cloudways-content'><?php echo $block->getData('widgetcontent'); ?></h2> <?php endif; ?>

Here, as you can see that I have picked up the value from fields by calling $block->getData(‘parameter’); where the parameters are widgettitle and widgetcontent.

And that’s it! We have successfully created a custom widget in Magento 2. It’s time to check the end-result. Login to your Magento 2 Admin panel and navigate to Content > Pages.

Magento 2 Content Page

Click Edit in front of Homepage CMS page.

Magento 2 CMS Page

Expand the Content tab and tap Insert Widget icon.

Magento 2 Insert Widget Icon

Select Cloudways Sample Widget from the widget list.

Magento 2 Sample Widget

Enter the Title and Content to display on the homepage, hit Insert Widget button and save the page.

Magento 2 Insert Widget

Lastly, in order to make any changes, you will have to flush the Magento 2 cache. Launch CLI and run the following commands:

php bin/magento cache:clean php bin/magento cache:flush

Load the front end of your store, and it will look like this.

Magento 2 Front Page

Conclusion

Well, this was all about creating a custom widget in Magento 2. The reason for writing this article is to provide you a precise tutorial starting from the basic steps, covering Magento 2 widget development, and calling it on the Magento 2 homepage.

If you have anything to add to this topic, feel free to share your thoughts in the comments section below.

Frequently Asked Questions

Q: What is a Magento widget?

A: A Magento widget is a customizable block that is used to display static or dynamic content at specific locations on store pages. Some widgets are available by default and you can also develop custom widgets to extend the native functionalities.

Q: What Magento 2 blocks are available by default?

A: Magento 2 offers the following blocks by default: CMS Page Link, CMS Static Block, Catalog Category Link, Catalog New Products List, Catalog Product Link, Catalog Products List, Orders and Returns, Recently Compared Products, Recently Viewed Products.

Q: How do I use Magento 2 widgets?

A:

Using Magento 2 widgets is a simple three-step process:

  1. Select the widget type in Content > Elements > Widgets
  2. Fill the fields in the Layout Updates section
  3. Place the Block

Remember to flush the cache so that the frontend loads the most recent display configurations.

Q: What is a block widget?

A: A block widget in Magento is essentially a non-editable block that is used as a placeholder for content on the pages. To use the block, you need the block ID.

Share your opinion in the comment section.COMMENT NOW

Customer Review at

“Great speed, features, knowledgebase, dashboard, UX and fast, expert support. Very happy!”

Stefan [Management Consultant]

Explore Cloudways

×

Thankyou for Subscribing Us!

Sours: https://www.cloudways.com/blog/magento-2-custom-widget/


3612 3613 3614 3615 3616