angelvilaplana/magewire-widget

Enable Magewire integration in widgets

1.0.0 2025-03-29 02:05 UTC

This package is auto-updated.

Last update: 2025-04-29 02:20:06 UTC


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.