The form consists of one question which has several answers, so that the answers can be dynamically created for each question. This stuff all 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 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 prototype template to populate container via jquery.
Adding new answer objects to the question object works fine. Deleting answers is also not a problem.
However, if I go to update existing property on one of the collection form inputs it does not update the existing object. It is persisting the question object though as it will update the text of the question itself. I can only delete and create new to replace something currently and I am having a hard time figuring out why.
Here is snippet of code from template form that is 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 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)));
}