Symfony subforms change setter function

153 Views Asked by At

On the database model I have a one-to-many relationship between contact and contactAddress.

I created 2 different forms in the ContactType i added the subform

$builder->add(
    'contactAddress',
    new ContactAddressType()
);

The contact entity class itself have this, but this entity is in another bundle and I can't change it.

private $contactAddresses;

public function addContactAddress(ContactAddress $contactAddresses)
{
    $this->contactAddresses[] = $contactAddresses;

    return $this;
}

public function removeContactAddress($contactAddresses)
{
    $this->contactAddresses->removeElement($contactAddresses);
}

public function getContactAddresses()
{
    return $this->contactAddresses;
}

The form is rendered correctly but when I submit the form I get the following error

Neither the property "contactAddress" nor one of the methods
"getContactAddress()", "contactAddress()", "isContactAddress()", 
"hasContactAddress()", "__get()" exist and have public access in class
"App\Bundle\ContactBundle\Entity\Contact".

when I change the field to contactAddresses the following error accured:

Neither the property "contactAddresses" nor one of the methods 
"addContactAddress()"/"removeContactAddress()", 
"setContactAddresses()", "contactAddresses()", "__set()" or "__call()" 
exist and have public access in class 
"App\Bundle\ContactBundle\Entity\Contact".

how I can use something like property_path to say how the property needed to be set, because it seems to use setContactAddresses which doesnt exist?

2

There are 2 best solutions below

1
On

I don't know if this would be causing the error described in the question but you cannot map a collection property to a single form type. In this case a Contact has many $contactAddresses, so $contactAddresses is a Collection. This means that to represent $contactAddresses in ContactType you need to add a collection field. For example:

$builder->add('contactAddresses', 'collection', array(
    'type'   => new ContactAddressType(),
    'options'  => array(
        ...
    ),
));

With such a form you can update the existing addresses but to add and remove addresses you will need to add some client side javascript. With a collection field, symfony provides some help with this. There is some information about this in the Symfony documentation for the Collection field type - Adding and removing items. However, for a collection of entities you probably need to look at the Cookbook entry How to embed a collection of forms.

0
On

I think you should embed a Collection of forms in your main form.

Read the docs.