Closed
Description
Based on the following documentation I tried to build a simple list filter based on checkboxes:
Code
FilterMachines.php
<?php
namespace App\Twig\Components;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\DefaultActionTrait;
#[AsLiveComponent('filter_machines')]
class FilterMachines
{
use DefaultActionTrait;
#[LiveProp(writable: true)]
public array $types = ['HYDRAULIC', 'AUTOMATIC', 'REPRISE'];
public function __construct(
) {
}
public function getMachines(): array
{
return array_filter([
['name' => 'Machine 1', 'type' => 'HYDRAULIC'],
['name' => 'Machine 2', 'type' => 'AUTOMATIC'],
['name' => 'Machine 3', 'type' => 'REPRISE'],
], fn($machine) => in_array($machine['type'], $this->types));
}
}
filter_machines.html.twig
<div {{ attributes }}>
<label for="type-hydraulic">hydraulic</label>
<input type="checkbox" data-model="types" id="type-hydraulic" value="HYDRAULIC">
<label for="type-automatic">automatic</label>
<input type="checkbox" data-model="types" id="type-automatic" value="AUTOMATIC">
<label for="type-reprise">reprise</label>
<input type="checkbox" data-model="types" id="type-reprise" value="REPRISE">
{% if computed.machines|length > 0 %}
<ul>
{% for machine in computed.machines %}
<li>
<strong>{{ machine.name }}</strong>
<p>{{ machine.type }}</p>
</li>
{% endfor %}
</ul>
{% else %}
<div>Ah! No machines found matching "{{ types }}"</div>
{% endif %}
</div>
index.html.twig (rendered by a dead simple FooController)
{% extends 'base.html.twig' %}
{% block title %}Hello HomeController!{% endblock %}
{% block body %}
{{ component('filter_machines') }}
{% endblock %}
To reproduce:
- Run the previous code
- Uncheck any checkbox
- See that nothing happens (no AJAX request, no component render)
Versions:
Symfony 6.2
Webpack Encore Bundle 1.17
UX LiveComponent 2.9