Create Widget Content in Page Builder
-
01-03-2021 - |
Question
I need to show in my home page a bestseller products list of certain category. To do so, i already created programmatically my own widget that lists bestseller products, but there's no way to drag a widget content with page builder. I know that i can drag a HTML content and insert there my widget, but i wonder if there's a better solution.
What's the best way to achieve it? Is there any way to extend Page Builder so i can add a widget type? Would you recommend any other option?
Solution
You have a couple of options. The simplest is using the Text content type to include the widget using the standard TinyMCE widget feature.
Your other option is to create a new content type which wraps your widget in a Page Builder content type. Our Products content type does exactly this, it's just an interface for the Catalog Product List widget.
products.xml
contains a mass converter to create the widget directive:
view/adminhtml/pagebuilder/content_type/products.xml
<converters>
<converter component="Magento_PageBuilder/js/content-type/products/mass-converter/widget-directive" name="widget_directive">
<config>
<item name="html_variable" value="html"/>
</config>
</converter>
</converters>
Which in turn within widget-directive.ts
(or JS depending on which source you're viewing) we create the standard product list widget directive:
view/adminhtml/web/ts/js/content-type/products/mass-converter/widget-directive.ts
:
public toDom(data: ConverterDataInterface, config: ConverterConfigInterface): object {
const attributes = {
type: "Magento\\CatalogWidget\\Block\\Product\\ProductsList",
template: "Magento_CatalogWidget::product/widget/content/grid.phtml",
anchor_text: "",
id_path: "",
show_pager: 0,
products_count: data.products_count,
type_name: "Catalog Products List",
conditions_encoded: this.encodeWysiwygCharacters(data.conditions_encoded || ""),
};
if (attributes.conditions_encoded.length === 0) {
return data;
}
set(data, config.html_variable, this.buildDirective(attributes));
return data;
}
You can read more about mass converters here: https://devdocs.magento.com/page-builder/docs/reference/configurations.html#mass-converter
You can look to duplicate the Products content type and modify it to your needs. On a high level, it just feeds it's configured form fields into the directive's parameters.
Alongside the above, we have a great step by step tutorial on how to create a new content type available here: https://devdocs.magento.com/page-builder/docs/create-custom-content-type/overview.html