How to work with a form on a beta version of Symfony2?

I have a User object and an organization address. There is a one-to-many relationship between the user and the address:

class User { /** * @orm:OneToMany(targetEntity="Address") */ protected $adresses; [...] } 

I have an AddressType class and a UserType class:

  class UserType extends AbstractType { public function buildForm(FormBuilder $builder, array $options) { $builder->add('addresses', 'collection', array('type' => new AddressType())); } [...] } 

In my controller, I create a form using

  $form = $this->get('form.factory')->create(new UserType()); 

... and create a view using:

  return array('form' => $form->createView()); 

I show the form field in my branch template:

  {{ form_errors(form.name) }} {{ form_label(form.name) }} {{ form_widget(form.name) }} [...] 

Good. Now, how to display fields for one or more addresses? (this is not {{ for_widget(form.adresses.zipcode) }} and {{ for_widget(form.adresses[0].zipcode) }} ...)

Any ideas?

+7
source share
2 answers

Here's how I did it in my form template:

 {{ form_errors(form.addresses) }} {% for address in form.addresses %} <div id="{{ 'address%sDivId'|format(loop.index) }}" class="userAddressItem"> <h5> Address #{{ loop.index }}</h5> {{ form_errors(address) }} {{ form_widget(address) }} </div> {% endfor %} 

And I have a small jQuery-driven action bar that allows the user to add and remove addresses. This is a simple script adding a new div to a container with the correct HTML code. For HTML, I just used the same output as Symfony, but with an updated index. For example, this will be the output for street text of the AddressType form:

<input id="user_addresses_0_street" name="user[addresses][0][street]" ...>

Then the next Symfony index will be set to 1, so the newly added input field will look like this:

<input id="user_addresses_1_street" name="user[addresses][1][street]" ...>

Note. Three points are a substitute for required="required" maxlength="255" , but may vary depending on your needs.

You will need more HTML code than adding a whole new AddressType to the DOM, but this will give you a general idea.

Yours faithfully,
Matt

+7
source

I should say that if you want to add fields dynamically, you need to set the "allow_add" key in the "Collection" field in UserType:

 ... $builder->add('addresses', 'collection', array( 'type' => new AddressType(), 'allow_add' => true )); 

I just spent hours trying to figure out what was missing, and while I am writing a document, this is not mentioned yet. Hope this helps other developers.

+5
source

All Articles