I have created a simple widget which displays dummy data. The problem is my front end code doesn't show up in my page ? I 'm working on Magento 2.2.0.
Here is my widget code what i want to display :
{{widget type="Widget\CustomWidget\Block\Widget\ContactInformations" fullname="Adrien" gender="mal" age="24"}}
widget/contact_informations code :
<?php
$fullname = $this->getData('fullname');
$age = $this->getData('age');
$gender = $this->getData('gender');
?>
<ul>
<?php if($fullname !=''){?>
<li><?php echo $fullname; ?></li>
<?php } ?>
<?php if($age !=''){?>
<li><?php echo $age; ?></li>
<?php } ?>
<?php if($gender!=''){?>
<li>
</li>
<?php } ?>
</ul>
etc/module.xml code :
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="Widget_CustomWidget" setup_version="1.0.0">
</module>
</config>
etc/widget.xml code :
<?xml version="1.0" encoding="UTF-8"?>
<widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Widget:etc/widget.xsd">
<widget id="widget_customwidget" class="Widget\CustomWidget\Block\Widget\ContactInformations">
<label translate="true">Contact Informations Widget</label>
<description>Widget in Magento2</description>
<parameters>
<parameter name="fullname" xsi:type="text" visible="true" sort_order="0" >
<label translate="true">Full Name</label>
</parameter>
<parameter name="age" xsi:type="text" visible="true" sort_order="10" >
<label translate="true">Age</label>
</parameter>
<parameter name="gender" xsi:type="select" source_model="Widget\CustomWidget\Model\Config\Source\Gender" visible="true" sort_order="10" >
<label translate="true">Gender</label>
</parameter>
</parameters>
</widget>
</widgets>
Widget/CustomWidget/Block/Widget/ContactInformations code :
<?php
namespace Widget\CustomWidget\Block\Widget;
class ContactInformations extends \Magento\Framework\View\Element\Template implements \Magento\Widget\Block\BlockInterface
{
public function _toHtml()
{
parent::_construct();
$this->setTemplate('widget/contact_informations.phtml');
}
}
Any idea ?
Best Answer
Your widget block
Widget\CustomWidget\Block\Widget\ContactInformations
should extend\Magento\Framework\View\Element\Template
otherwise it can't be displayed.Everything is ok in your configuration code. However your Block code is wrong. You shouldn't override _tomHtml() in this case but define your template as
protected $_template = 'widget/contact_informations.phtml'
. Your template must be stored to this path, at the root of your module:/view/frontend/widget/contact_informations.phtml