我试图创建一个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 SymfonyComponentFormAbstractType;
use SymfonyComponentFormExtensionCoreTypeTextType;
use SymfonyComponentFormFormBuilderInterface;
use AppLocaleProvider;
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);