Sometimes you may need to embed forms in Symfony with no related entities, no OneToMany or other relation, you can just add a form inside another as you would do with a new field. The reason to do this could be to group the two forms inside a single action to submit all data in one click, for example. These two entities are not mapped to each other, they are just there for the sake of a grouped action.
// Parent form
public function buildForm(FormBuilderInterface $builder, array $options)
{
// Add nested form
$builder->add('article', new ArticleNestedType(
$this->em // Pass parameters to nested form if any
),
array('data' => new Article())); // Pass options parameters to nested form
}
In controller, handle data base actions when form is submitted:
if ($form->isValid()) {
// Persist new Entity
if (true === isset($form->getData()['article'])) {
$article = $form->getData()['article'];
$em = $this->getDoctrine()->getManager();
$em->persist($article);
$em->flush();
}
}
Then in twig to display child form:
{{ form_widget(form.article) }}