The form consists of one question, which has several answers, so that answers can be dynamically created for each question. This stuff works fine:
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('question','textarea') ->add('answers', 'collection', array( 'type'=>new AnswerType(), 'allow_add'=>true, 'allow_delete'=>true, 'label' => false )) ; }
Here is the form code for AnswerType:
$builder ->add('answer','text', array( 'attr'=>array( 'class'=>'form-control' ), 'label'=>false )) ->add('isGoodAnswer', 'checkbox', array( 'label'=>'Good?', 'required'=>false )) ;
I am using a prototype template to populate a container through jquery.
Adding new answer objects to the question object works fine. Removing answers is also not a problem.
However, if I proceed to update an existing property on one of the inputs of the collection form, it does not update the existing object. It saves the question object, although it will update the text of the question itself. I can only delete and create a new one to replace something now, and itβs hard for me to understand why.
Here is the code snippet from the template form that was submitted:
<ul id="answer-fields-list" data-prototype="{{ form_widget(form.answers.vars.prototype)|e }}"> {% for answer in form.answers %} <li> <div class='col-md-12'> {{ form_widget(answer) }} <div> <a href='#' class='btn btn-sm btn-danger delete-this'><span class='glyphicon glyphicon-trash'></span></a> </div> </div> </li> {% endfor %} </ul> <a href="#" id="add-answer" class='btn btn-sm btn-success'><span class='glyphicon glyphicon-plus-sign'></span> Add Answer</a>
edit, here is the full controller code for this update method:
$question = $em->getRepository('ChecklistMainBundle:ChecklistQuestion')->findOneById($questionId); if(!$question) throw new NotFoundHttpException('Question not found'); $form = $this->createForm(new QuestionAnswerType(), $question); $form->handleRequest($request); if($request->getMethod()=='POST' && $form->isValid()) { if($form->get('attachment')->getData() != null) { $question->uploadAttachment(); } $em->persist($question); $em->flush(); $this->get('session')->getFlashBag()->add('success', 'Question was modified successfully!'); return $this->redirect($this->generateUrl('admin_checklists_view', array('id'=>$id))); }