Php 如何在没有任何自定义表单类型类的情况下创建多个字段的集合?
我有很多集合要创建,不想为每个条目类型创建FormType,因为它们只使用一次 因此,我没有在Php 如何在没有任何自定义表单类型类的情况下创建多个字段的集合?,php,forms,collections,symfony,Php,Forms,Collections,Symfony,我有很多集合要创建,不想为每个条目类型创建FormType,因为它们只使用一次 因此,我没有在entry\u type选项中给出表单类型FQCN,而是尝试直接从表单生成器中输入一个新的type: $type = $this ->get('form.factory') ->createBuilder(Type\FormType::class) ->add('label', Type\TextType::class, [ 'label' =>
entry\u type
选项中给出表单类型FQCN,而是尝试直接从表单生成器中输入一个新的type
:
$type = $this
->get('form.factory')
->createBuilder(Type\FormType::class)
->add('label', Type\TextType::class, [
'label' => 'Key',
])
->add('value', Type\TextType::class, [
'label' => 'Value',
])
->getType()
;
$form = $this
->get('form.factory')
->createBuilder(Type\FormType::class)
->add('hash', Type\CollectionType::class, [
'entry_type' => $type,
'entry_options' => [],
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'required' => false,
'delete_empty' => true,
])
->getForm()
;
但由于某些原因,原型无效:
<div class="form-group">
<label class="control-label required">__name__label__</label>
<div id="form_hash___name__"></div>
</div>
__名称标签__
手动创建的
$type
中的所有子字段都丢失。我的错在哪里?我终于自己找到了答案
由于我使用的->getType()
在FormBuilder
类中,但不在FormBuilderInterface
中,因此我认为使用它是个坏主意。此外,返回的FormType
实例为空(一个表单类型,但没有子级)
因此,我改变了立场,创建了以下EntryType
类(是的,我使用的是一个表单类型类,但对于我未来的所有集合,只使用一个通用类):
实际上,它需要一个FormTypeInterface()。我没有意识到它采用了FormType,这就是为什么我删除了我的评论。我认为应该可以使其工作,但不确定如何工作。FormBuilder中的getType方法不参与FormBuilderInterface,因此我不确定当前使用的方法是否有效。如果确实出现问题,您可能会遇到异常。我看了一下代码,但每当我试图深入研究表单时,我的大脑就会变得非常不稳定。可能希望用简单的表单(表单)替换模板,以确保渲染过程中没有任何问题。为了完成我的回答,下面是一篇关于“如何向现有类型添加选项”的有趣文章:
<?php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class EntryType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
foreach ($options['fields'] as $field) {
$builder->add($field['name'], $field['type'], $field['options']);
}
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'fields' => [],
]);
}
}
use Symfony\Component\Form\Extension\Core\Type;
use AppBundle\Form\Type\EntryType;
// ...
$form = $this
->get('form.factory')
->createBuilder(Type\FormType::class)
->add('hash', Type\CollectionType::class, [
'entry_type' => EntryType::class,
'entry_options' => [
'fields' => [
[
'name' => 'key',
'type' => Type\TextType::class,
'options' => [
'label' => 'Key',
],
], [
'name' => 'value',
'type' => Type\TextType::class,
'options' => [
'label' => 'Value',
],
],
],
],
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'required' => false,
'delete_empty' => true,
])
->getForm()
;