首页 > 解决方案 > 在 symfony 中为子表单添加表单域

问题描述

Symfony 4.1

这是我的个人表单类型:

class PersonalType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstName', TextType::class, [
                'required' => true,
                'attr'     => [
                    'placeholder' => 'First name'
                ],
            ])
    //......

这是我的 ClientType 使用 PersonalType 作为子表单

    class ClientType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
      $client = $builder->getData();
        $builder
            ->add('personalDetails', PersonalType::class, [
                'data' => $client
            ])
//....

我已经向子表单类型添加了一个事件侦听器,但是它没有被调用,所以我将事件侦听器移到了 ClientType。

我想向 PersonalType 添加一个字段,我这样做了:

$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
          $client = $event->getData();
          $form = $event->getForm();

$form->add('title', TextType::class, [
   'type' => new PersonType(),
    'label' => 'Title'
]
    }

但我有一个错误说option "type" does not exists

我在这里想念什么?

标签: formssymfony4

解决方案


['type' => ...] 选项不是 Symfony 的 TextType 的有效选项。有关有效选项,请参阅此处的参考:https ://symfony.com/doc/current/reference/forms/types/text.html 。您还可以在此处查看其他内置表单类型的有效选项:https ://symfony.com/doc/current/reference/forms/types.html 。

也许您已经看到了一个自定义表单类型,它通过使用带有or的configurationOptions方法来定义“类型”选项(参见此处:https ://symfony.com/doc/current/form/create_custom_field_type.html )。我猜这是来自您的 PersonType。TextType 不支持。setDefaultssetRequired

我不确定你到底想做什么

   'type' => new PersonType(),

线。如果您只是想将“title”字段添加到您的 PersonType,并且由于某种原因您想使用事件侦听器而不是直接在 PersonType 类中执行此操作(在大多数情况下这将是最简单的选项),它感觉只是删除那条线就足以让它工作?


推荐阅读