view raw
mrmabx mrmabx - 10 months ago 74
PHP Question

Edit multiple entities in one form

I have a Entity

and form type for editing Question
. I can successfull edit one Question. Now i create a link for editing all Questions.

I would like to edit all Questions in one form, how can i handle this? I try to use collections, but i don't know how to map a single question in a form collection and I'm not sure if that's the right approach.

look like:

public function buildForm(FormBuilderInterface $builder, array $options)
$categories = $this->entityManager->getRepository('MyAppBundle:QuestionCategory')->findByIsActive(true);

$builder->add('category', 'entity', array(
'class' => 'MyAppBundle:QuestionCategory',
'choices' => $categories,
'label' => 'category',
'translation_domain' => 'messages',
'multiple' => false,
'empty_value' => 'msg.pleaseSelect',
'expanded' => false))
->add('translations', 'a2lix_translations', array(
'fields' => array(
'text' => array(
'field_type' => 'textarea',
'label' => 'hintText',
'attr' => array('class' => 'rte')
'explanation' => array(
'field_type' => 'textarea',
'label' => 'title',
'attr' => array('class' => '')

public function setDefaultOptions(OptionsResolverInterface $resolver)
'data_class' => 'My\AppBundle\Entity\Question',

My Controller with action to edit all Questions, look like:

$em = $this->getDoctrine()->getManager();
$questions = $em->getRepository('MyAppBundle:Question')->findAll();

* -- Here is my problem , how can i my $questions into form? ---
$form = $this->createFormBuilder()
->add('questions', 'collection', array(
'type' => new QuestionType() ,
'allow_add' => false,
'allow_delete' => false,
'label' => false)
->add('save', 'submit', array('label' => 'Create'))


if ($form->isValid()) {

return $this->render('MyAppBundle:Question:editAllQuestions.html.twig', array("form" => $form->createView()));

Has anyone a hint or approach?


You're on the right track, what you probably want to do is:

$form->setData(array('questions' => $yourQuestionArray));

Just after ->getForm() but before ->handleRequest($request).

Or you could pass it as an option to createFormBuilder() like so:

$form = $this->createFormBuilder(array('questions' => $yourQuestionArray))

They both do the same thing.

Ordinarily when you create a form class (which it looks like what you're doing with QuestionType), you provide a data_class configuration option (see documentation) that defines what the form uses as its model.

What you're doing in your controller is creating a kind of "anonymous" form that doesn't have an associated data class (documentation, this looks like what you're doing in your controller). In which case its data is an array (similarly if you called $form->getData() you'd get an array back).