以空symfony形式嵌入嵌套的表单类型字段

时间:2018-12-13 11:07:58

标签: php forms doctrine symfony4

我有一个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,
        ));
    }
}

1 个答案:

答案 0 :(得分:0)

是的。解决了。 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'))。