Data binding with nested Twig components for arrays? #2819
Replies: 1 comment
-
Data binding with nested Twig components for arrays (UX Live Components)Short answer: Use a single This works with UX Live Components; arrays are supported as LiveProp values. 1) Live component class// src/Twig/Components/Filters.php
namespace App\Twig\Components;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
#[AsLiveComponent('filters')]
final class Filters
{
/** @var string[] */
#[LiveProp(writable: true)]
public array $lists = []; // will contain selected values, e.g. ['a', 'b']
}
2) Nested Checkbox Twig component{# templates/components/Checkbox.html.twig #}
{% props class = '', value = '' %}
{% set checkbox = html_cva(
base: 'h-4 w-4 shrink-0 rounded-xs border border-primary ring-offset-background focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground',
) %}
<input
type="checkbox"
value="{{ value }}"
class="{{ checkbox.apply({}, class) | tailwind_merge }}"
{{ attributes|raw }}
/> Important: we do not hardcode 3) Parent Live template using the nested component{# templates/components/Filters.html.twig #}
<twig:Checkbox data-model="lists" value="news" class="mr-2" />
<twig:Checkbox data-model="lists" value="sports" class="mr-2" />
<twig:Checkbox data-model="lists" value="tech" class="mr-2" />
{# Debug output #}
<div class="mt-2 text-sm">Selected: {{ lists|join(', ') }}</div> Notes:
4) If you also render this from a Symfony FormIf your checkbox component is used inside a Form row and you need <input
type="checkbox"
name="{{ attributes.name ?? 'lists[]' }}"
value="{{ value }}"
{{ attributes|raw }}
/> LiveComponents relies on 5) Common gotchas
References
TL;DRUse |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Checkbox component
This is similar to the Checkbox component @Kocal has been working on in the shadcn Toolkit.
https://github.com/symfony/ux/blob/2.x/src/Toolkit/kits/shadcn/docs/components/Checkbox.md
My goal is to use data binding like this.
In the docs I read that I can use
dataModel
instead, however I can't get it to work for arrays[]
like in the docs.Any ideas?
Beta Was this translation helpful? Give feedback.
All reactions