具有 predefined/static 行的 Symfony 表单 CollectionType

Symfony Form CollectionType with predefined/static rows

我正在尝试创建一个包含 predefined/static 行的 CollectionType 表单(不是动态表单 w/JS)。

这就是我想要的:

$formBuilder = $this->createFormBuilder()->add('titles', CollectionType::class, [
    'entry_type' => TextType::class,
    'data' => ['en' => '', 'de' => ''],
]);

但这不起作用(它导致表单中根本没有行):

$formBuilder = $this->createFormBuilder()->add('titles', CollectionType::class, [
    'entry_type' => TextType::class,
]);
$formBuilder->get('titles')->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
    $data = ['en' => '', 'de' => ''];
    $event->setData($data);
});

最后,我正在寻找一个像这样的简单表格:

<form name="form" method="post">
    <div id="form">
        <div><label>Titles</label>
            <div id="form_titles">
            <div><label for="form_titles_en">En</label>
                <input type="text" id="form_titles_en" name="form[titles][en]">
            </div>
            <div><label for="form_titles_de">De</label>
                <input type="text" id="form_titles_de" name="form[titles][de]">
            </div>
        </div>
    </div>
</form>

出于各种原因,我需要第二种方法。有人有解决办法吗?

仅供参考:我当前的平台是 Symfony 5.4 和 Php 8.1,但我希望此解决方案适用于 Php7.4 以及 Symfony 6+

感谢@Bossman 给我指导。我就是这样解决问题的。

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use App\LocaleProvider;

class TranslationCollectionType extends AbstractType
{
    private LocaleProvider $localeProvider;

    public function __construct(LocaleProvider $localeProvider)
    {
        $this->localeProvider = $localeProvider;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        foreach ($this->localeProvider->getSupportedLocaleNames() as $name => $value) {
            $builder->add($value, TextType::class, [
                'label' => $name,
            ]);
        }
    }
}

然后在表格中添加:

$builder->add('Titles', TranslationCollectionType::class);