Symfony Embedded Forms ‘take 2’

Learnt some new things while working with symfony’s embedded forms, as we know, when they are have relations in the entities that the form is modelled after you want to ensure that when including the other form type that you create an instance of the formType representing the many in the manyToOne relationship. For example in the forum i am working on (which you can find on github here though currently still in development as of the date of this blog entry) a Topic has MANY Posts, as a result, we build our form by instantiating the PostType first and then adding the TopicType to it as a field because the PostType has a related Topic in the database schema.

But following up from the last post, what about when we have unique use cases for our form Types? What if we want to use a PostType without including the TopicType or we wish to conditionally decide wether for the purposes of editing we need to populate the form before presenting it?

To make this easier, in my FormHandlers what i choose to do is pass an array with some options we can use, namely a mode key specifies wether we are to ‘insert’ or ‘update’ an entity, and other keys for holding the entity to populate the form if mode is ‘update’

Here is an example from the top half of my TopicFormHandler:

class TopicFormHandler
	protected $factory;
	protected $request;
	protected $options;
	protected $form;

	public function __construct($factory, Request $request, array $options = null )
		$this->factory = $factory;
		$this->request = $request;
		$this->options = $options;
		if ($this->options['mode'] == 'update')
			$this->form = $factory->create(new PostType(), $this->options['post']);
			$this->form->add($factory->create(new TopicType(), $this->options['post']->getTopic()));
			$this->form = $factory->create(new PostType());
			$this->form->add($factory->create(new TopicType()));

To view the full source in greater context, explore the source on github here.