How the Wire demo works
Bellow is the code used to implement the dynamic component on /wire-demo
The TWIG Template
<input
wire:model="myString"
type="text"
placeholder="Type in something"
required
>
{% if myString %}
<div>
<button wire:click="decrement">-N</button>
<button wire:click="increment">N+</button>
</div>
<p>
Submit to process data on the server which will repeat
"<span>{{ myString }}</span>" input
"<span>{{ count }}</span>" times
</p>
<small>*Observe the Network tab in the console</small>
<div>
<button wire:click="doAction" type="submit">
Submit
</button>
<div wire:click="resetValues">
<span>Reset</span>
</div>
</div>
{% endif %}
{% if results %}
{% for result in results %}
<p>{{ result }}</p>
{% endfor %}
{% endif %}
PHP Class component
namespace Drupal\wire\Plugin\WireComponent;
use Drupal\wire\View;
use Drupal\wire\Wire;
use Drupal\wire\WireComponentBase;
/**
* Wire Demo component.
*
* @WireComponent(
* id = "wire_demo_component",
* )
*/
class WireDemoComponent extends WireComponentBase {
public int $count = 1;
public string $myString = '';
public ?array $results = [];
protected array $queryString = [
'myString' => ['except' => ''],
'count' => ['except' => 1],
];
public function increment() {
$this->count++;
}
public function decrement() {
$this->count > 1 && $this->count--;
}
public function doAction() {
$this->results = [];
for ($i = 0; $i < $this->count; $i++) {
$this->results[] = $this->myString;
}
}
public function resetValues() {
$this->count = 1;
$this->myString = '';
$this->results = [];
}
public function render(): ?View {
return View::fromTpl('wire_demo_component');
}
}