Skip to content

[Live Component] Try to make an array of input #1787

@marcteyssier

Description

@marcteyssier

Hi,

In my project, I want to make my own array to build a form with it.
The project is to be able to enter times for a given project per day. It will be possible to do one visualization per week or per month.
Also I don't want to use an entity directly, but use an array that I will transform into an entity when saving.
Like this (example for week)
image

But, when I try to build the form in twig with loop "for" it doesn't work.
Because the "key" variable in foor loop is not interpreted as a variable, but a character string

<?php

namespace App\Component;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent]
final class Index extends AbstractController
{
    use DefaultActionTrait;

    #[LiveProp(writable: true)]
    public array $timeList = [['project' => 'a', 'timeList' => [0,0,0,0,0]]];

    #[LiveAction]
    public function addLine() {
        $this->timeList[] = ['project' => '', 'timeList' => [0,0,0,0,0]];
    }
}
<div{{ attributes }}>
    {{ dump(timeList) }}
    <button data-action="live#action"
            data-live-action-param="addLine">Add Line</button>

    {# doesn't work because varialbe key is reading like an string and not variable #}
    {# error : Uncaught Error: Invalid model name "timeList.key.project" #}
    {% for key, timeItem in timeList %}
        <input data-model="timeList[key].project"/>
    {% endfor %}

    {# This work #}
    <input data-model="timeList[0].project"/>
</div>

So I try to make a sub live component, but the parent array isn't update.

Like this

<div{{ attributes }}>
    {{ dump(timeList) }}
    {% for key, timeItem in timeList %}
            {{ component("Time", {
                    dataModel: "timeList["~key~"][project]:project"
            }) }}
    {% endfor %}
</div>

image

I looked at this example https://ux.symfony.com/demos/live-component/invoice, but I would like to have a global save and not a per line save.

Have you an idea to make this project ?

Thanks
Marc

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions