在空的 symfony 表单中嵌入嵌套表单类型字段

Embedding nested form type fields in empty symfony form

我有一个 Shop 实体的表单类型。这以 1-1 关系链接到 ShopAddress 实体。

当我嵌套 ShopAddress 实体时 appears blank 创建新商店。创建新 Shop 时,我怎样才能使它与相关的空白字段一起呈现?

// App/Froms/ShopType.php
class ShopType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add( "name" ) // rendering fine
            ->add( "shopAddress", CollectionType::class, [
                "entry_type" => ShopAddressType::class, // no visible fields
            ] )
        ;
    }


    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            "data_class" => Shop::class,
        ));
    }
}

// App/Froms/ShopAddressType.php
class ShopAddressType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add("addressLine1", TextType::class ) // not rendering
            ->add("addressLine2") // not rendering
            ->add("postcode") // not rendering
            ->add("county"); // not rendering
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            "data_class" => ShopAddress::class,
        ));
    }
}

是的。解决了。 Docs had the answer 您需要将其作为新的 FormBuilderInterface 对象添加到 add() 方法中:

class ShopType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add("name", TextType::class)
            ->add(
                // nested form here
                $builder->create(
                    'shopAddress', 
                    ShopAddressType::class, 
                    array('by_reference' => true ) // adds ORM capabilities
                )
            )
        ;
    }


    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            "data_class" => Shop::class,
        ));
    }
}

添加 array('by_reference' => true ) 将允许您使用完整的 ORM(在我的例子中是 Doctrine)功能(例如 $shop->getAddress()->setAddressLine1('this string to add'))。