You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Twill3 CMS:如何用组件表单构建器创建可重复CardItem的CardContainer区块

在Twill3中实现CardContainer作为CardItem区块的重复器

核心思路

CardContainer作为父区块,需要通过重复器组件(Repeater/InlineRepeater)引用已注册的CardItem区块类型,而非直接实例化CardItem组件。关键是确保CardItem区块已正确注册,且重复器的type()参数与CardItem的区块类型名完全一致。


步骤1:确认CardItem区块的注册与配置

首先保证CardItem区块已在Twill中注册,且定义了正确的区块类型名:

// app/Twill/Blocks/CardItem.php
class CardItem extends Block
{
    // 定义区块类型标识,后续重复器将引用此值
    public static $type = 'card-item';

    public function getForm(): Form
    {
        return Form::make([ 
            Medias::make()->name('image')->label(twillTrans('Card-Bild')),
            Browser::make()->name('href')->label(twillTrans('Card-Link'))->modules($this->browsableClasses)->max(1),
            Input::make()->name('title')->label(twillTrans('Card-Titel'))->translatable(),
            Checkbox::make()->name('overlay')->label(twillTrans('Titel überlagern')),
            Wysiwyg::make()->name('text')->label(twillTrans('Card-Text'))->translatable()->toolbarOptions($this->wysiwygOptions)->browserModules($this->browsableClasses),
        ]);
    }
}

在TwillServiceProvider中注册两个区块:

// app/Providers/TwillServiceProvider.php
public function registerBlocks()
{
    $this->registerBlock(\App\Twill\Blocks\CardItem::class);
    $this->registerBlock(\App\Twill\Blocks\CardContainer::class);
}

步骤2:编写CardContainer的表单构建代码

根据编辑场景选择重复器类型,以下是两种常用实现:

选项1:使用Repeater(弹出模态框编辑子项)

适合字段较多、编辑逻辑复杂的场景:

// app/Twill/Blocks/CardContainer.php
public function getForm(): Form
{
    return Form::make([
        Repeater::make()
            ->name('cards') // 存储子项数据的字段名
            ->label(twillTrans('Karten'))
            ->type('card-item') // 对应CardItem的$type值
            ->buttonText(twillTrans('Karte hinzufügen'))
            ->max(10) // 可选:限制最大添加数量
            ->min(1), // 可选:限制最小数量
    ]);
}

选项2:使用InlineRepeater(内联编辑子项)

适合字段较少、希望在当前页面直接编辑的场景:

// app/Twill/Blocks/CardContainer.php
public function getForm(): Form
{
    return Form::make([
        InlineRepeater::make()
            ->name('cards')
            ->label(twillTrans('Karten'))
            ->type('card-item')
            ->buttonText(twillTrans('Karte hinzufügen'))
            ->collapsible(), // 可选:允许折叠子项简化视图
    ]);
}

三种重复器类型的区别

  • Repeater:点击添加按钮后弹出模态框编辑子项,适合复杂字段结构
  • InlineRepeater:子项直接展示在当前表单页面内,编辑更直观,适合简单字段
  • JsonRepeater:将子项数据存储为JSON格式(而非关联表),适合不需要单独管理子项的轻量场景,区块重复器一般较少使用

之前代码的问题说明

  • (new CardItem)->repeater('cards'):Twill表单构建器不支持直接实例化区块组件作为重复器字段,必须通过注册的区块类型名引用
  • type('blikk-carditem'):若CardItem的$type不是该值,系统无法找到对应的区块类型,需确保名称完全匹配
  • type('text'):这是引用Twill内置的文本类型,而非自定义的CardItem区块,因此无法加载CardItem的表单字段

内容的提问来源于stack exchange,提问作者Onki Hara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 23:12:19