Filippo Andrighetti
Filippo Andrighetti

Reputation: 13

Symfony2 - Nested form with nested objects

I'm quite new to Symfony and I'm trying to make a nested form with entities to reduce code duplication, it's easiest to explain with code. I followed the example on the doc (How to Reduce Code Duplication with inherit_data), so I created two entities:

class Company {
    private $name;
    private $website;
    private $fullAddress;
    // Getters and Setters
}

class Customer {
    private $firstName;
    private $lastName;
    private $fullAddress;
    // Getters and Setters
}

Now I want to reduce the code creating a third entity, called FullAddress:

class FullAddress {
    private $address;
    private $zipcode;
    private $city;
    private $country;
    // Getters and Setters
}

After that I created three Form like on the example:

$builder
    ->add('name', 'text')
    ->add('website', 'text')
    ->add('fullAddress', new FullAddressType(), array(
        'data_class' => 'AppBundle\Entity\Company'
    ));

But in the controller when I try to create a CompanyType, Symfony tries to search every fullAddress field in the main class (Company and Customer) giving an error (for example $address is not public or there isn't a get method in the class Company). Is there a way fix this, forcing Symfony to search for the desired field in a nested object?

I also tried to play with data_class and inherit_data attributes, changing the Class to FullAddress instead of Company, but the problem always occurs.

Thanks.

Upvotes: 1

Views: 2200

Answers (1)

Richard
Richard

Reputation: 4119

I'd go with a simpler approach. Create an Address entity and add a relation to both Customer and Company entities. An address is a very generic thing so there's no real reason why both Customer and Company can't just share that Address entity.

Then you can just create a generic AddressType form type and include it as a nested form type in your CompanyType and CustomerType forms. Much simpler to deal with and you're still following DRY principles.

Upvotes: 1

Related Questions