的形式由哪幾種答案,這樣的答案可以爲每個問題被動態地創建一個問題。這東西一切工作正常:Symfony2的形式,對象的集合,發行更新現有對象屬性
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
))
;
}
這裏是AnswerType表單代碼:
$builder
->add('answer','text', array(
'attr'=>array(
'class'=>'form-control'
),
'label'=>false
))
->add('isGoodAnswer', 'checkbox', array(
'label'=>'Good?',
'required'=>false
))
;
我使用的原型模板通過jQuery來填充容器。
添加新的答案對象的問題對象工作正常。刪除答案也不是問題。
但是,如果我去上收集表單輸入時不更新現有的對象一個更新現有的財產。它堅持問題對象,因爲它會更新問題本身的文本。我只能刪除並創建新的目前替換的東西,我很難找出原因。
下面是從模板形式的代碼片段提交:
<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>
編輯,這裏是本次更新的方法全控制器代碼:
$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)));
}
你應該共享的代碼,其中代碼段你處理輸入 – 2014-12-01 23:27:58
嘿米迦勒,我只是做'$ form-> handleRequest($ request);'然後堅持$問題對象。這個表單是通過symfony2表單生成器'$ form = $ this-> createForm(new QuestionAnswerType(),$ question);' – skrilled 2014-12-02 20:36:14
創建的,只是爲了闡明我的理解是正確的:你的更改持久存在於數據庫中,但是對象不是在PHP代碼中進行了修改,表單用老東西渲染,對吧?你的方法看起來很好(通過本書)。我要求輸入代碼片段,因爲可能存在重新創建對象,再次呈現它,從數據庫而不是表單等讀取它的一些小錯誤。 – 2014-12-03 08:11:55