演示 / Live Component

嵌入式 CollectionType 表单

解锁 Symfony CollectionType 的潜力,无需编写任何 JavaScript。此演示展示了完全在 PHP 和 Twig 中添加和删除项目。

项目 优先级
// ... use 语句已隐藏 - 点击显示
use App\Entity\TodoList; use App\Form\TodoListFormType; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Form\FormInterface; use Symfony\UX\LiveComponent\Attribute\AsLiveComponent; use Symfony\UX\LiveComponent\Attribute\LiveProp; use Symfony\UX\LiveComponent\DefaultActionTrait; use Symfony\UX\LiveComponent\LiveCollectionTrait;

#[AsLiveComponent]
class TodoListForm extends AbstractController
{
    use DefaultActionTrait;
    use LiveCollectionTrait;

    #[LiveProp(fieldName: 'formData')]
    public ?TodoList $todoList;

    protected function instantiateForm(): FormInterface
    {
        return $this->createForm(
            TodoListFormType::class,
            $this->todoList
        );
    }
}
<div
    {{ attributes }}
>
    {{ form_start(form) }}
        <div class="row">
            <div class="col-4">
                {{ form_row(form.name, {
                    label: false,
                    attr: {
                        placeholder: 'Give your list a name'
                    }
                }) }}
            </div>
        </div>

        <table class="table table-borderless form-no-mb">
            <thead>
                <tr>
                    <td>Item</td>
                    <td>Priority</td>
                </tr>
            </thead>
            <tbody>
                {% for item_form in form.todoItems %}
                    <tr>
                        <td>
                            {{ form_row(item_form.description, {
                                label: false,
                                row_attr: {class: 'mb-1'},
                                attr: {
                                    placeholder: 'Walk the pygmy hippo'
                                }
                            }) }}
                        </td>
                        <td>
                            {{ form_row(item_form.priority, {
                                row_attr: {class: ''},
                                label: false,
                            }) }}
                        </td>
                        <td>
                            {{ form_row(item_form.vars.button_delete, {label: 'X', attr: {class: 'btn btn-outline-danger'}}) }}
                        </td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>

        {{ form_widget(form.todoItems.vars.button_add, {label: '+ Add Item', attr: {class: 'btn btn-outline-primary'}}) }}

        <button type="submit" class="btn btn-success" formnovalidate>Save</button>
    {{ form_end(form) }}
</div>
作者 weaverryan
发布 2022-06-17