angelvilaplana / magewire-widget
Enable Magewire integration in widgets
Installs: 58
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
Type:magento2-module
Requires
- magewirephp/magewire: ^1.11
README
Enables adding widgets using the Magewire library without any errors.
Installation
composer require angelvilaplana/magewire-widget
Usage
Create a new widget based on this https://github.com/magewirephp/magewire/blob/main/docs/Features.md#widgets-dc.
Example
- 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="Vendor\Module\Block\Widget\Counter" id="magewire_counter_widget"> <label>Magewire counter</label> <description>Test Magewire widget</description> </widget> </widgets>
- Block/Widget/Counter.php
namespace Vendor\Module\Block\Widget; use Vendor\Module\Magewire\Counter as CounterWidget; use Magento\Framework\App\ObjectManager; use Magento\Framework\View\Element\Template; use Magento\Widget\Block\BlockInterface; class Counter extends Template implements BlockInterface { protected $_template = 'widget/counter.phtml'; public function __construct( Template\Context $context, array $data = [] ) { $data['magewire'] = ObjectManager::getInstance()->create(CounterWidget::class); parent::__construct($context, $data); } }
- Magewire/Counter.php
<?php declare(strict_types=1); namespace Vendor\Module\Magewire; use Magewirephp\Magewire\Component; class Counter extends Component { public int $count = 0; public function increment(): void { $this->count++; } }
- view/frontend/templates/widget/counter.phtml
<?php /** * @var \Vendor\Module\Magewire\Counter $magewire */ ?> <div> <h1><?= $magewire->count ?></h1> <button wire:click="increment()">+</button> </div>
When you have all the files created, you can add the widget to a CMS page or block. The widget will be rendered correctly.