0

I have form type for a Shop entity. This links in a 1-1 relationship to a ShopAddress entity.

When I nest the ShopAddress entity it appears blank when creating a new shop. How can I get this to render with the relevant blank fields when creating a new 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

1 Answer 1

1

Yep. Solved it. Docs had the answer You need to add it as a new FormBuilderInterface object in the add() method:

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,
        ));
    }
}

Adding array('by_reference' => true ) will allow you to use the full ORM (Doctrine in my case) capabilities (e.g. $shop->getAddress()->setAddressLine1('this string to add')).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.