我在Symfony2中有一个显示在Twig模板上的表单。我想知道Controller的业务逻辑是什么,可以将用户条目保存到数据库中?我尝试了下面的代码,但它没有插入数据库。非常感谢:))
/**
* @Route("/lot", name="sort")
* @Template()
*/
public function bestAction(Request $request)
{
$quest = new quest();
$form = $this->createForm(new QuestType(), $quest, array(
// 'action' => $this->generateUrl('best'),
'method' => 'POST',
));
$form->handleRequest($request);
if($entity->isValid()){
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('IWABundle:quest');
$em->persist($entity);
$em->flush();
}
return $this->render('IWABundle:Default:index.html.twig', array(
'form' => $form->createView()
));
}

{% block form %}
{{ form_start(form, {'action': path('sort'), 'method':'POST'}) }}
{{ form_start(form.email) }}
{{ form_start(form.firstname) }}
{{ form_start(form.enqiry) }}
{{ form_end(form) }}
{% endblock %}

答案 0 :(得分:0)
您正在将实体($quest
)与实体管理器混合:
/**
* @Route("/lot", name="sort")
* @Template()
*/
public function bestAction(Request $request)
{
// 1) Create your empty entity
$quest = new Quest();
// 2) Create your form from its type and empty entity
$form = $this->createForm(new QuestType(), $quest, array(
'method' => 'POST',
));
// 3) Handle the request
$form->handleRequest($request);
// 4) Check if the form is valid
if ($form->isValid()) {
// 5) Get the entity manager
$em = $this->getDoctrine()->getEntityManager();
// 6) Persist the new entity and flush the changes to the database
$em->persist($quest);
$em->flush();
}
return $this->render('IWABundle:Default:index.html.twig', array(
'form' => $form->createView()
));
}
查看how to persist objects to the database和how to manage form submission上的官方文档。