php - symfony2 form, collection of objects, issue updating existing object property -
the form consists of 1 question has several answers, answers can dynamically created each question. 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 form code answertype:
$builder ->add('answer','text', array( 'attr'=>array( 'class'=>'form-control' ), 'label'=>false )) ->add('isgoodanswer', 'checkbox', array( 'label'=>'good?', 'required'=>false )) ;
i using prototype template populate container via jquery.
adding new answer objects question object works fine. deleting answers not problem.
however, if go update existing property on 1 of collection form inputs not update existing object. persisting question object though update text of question itself. can delete , create new replace , having hard time figuring out why.
here snippet of code template form submitted:
<ul id="answer-fields-list" data-prototype="{{ form_widget(form.answers.vars.prototype)|e }}"> {% 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 full controller code 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 modified successfully!'); return $this->redirect($this->generateurl('admin_checklists_view', array('id'=>$id))); }
after searching through google hours ran across duplicate question resembles mine.
how force doctrine update array type fields?
i adjusted setanswers method follows reflect answer:
public function setanswers($answers) { if(!empty($answers) && $answers === $this->answers) { reset($answers); $answers[key($answers)] = clone current($answers); } $this->answers = $answers; return $this; }
it saves existing answers fine, no more issues :)
Comments
Post a Comment