2015-08-08 111 views
-2

我在Symfony2中有一個表單顯示在Twig模板上。我想知道什麼是控制器的業務邏輯,將用戶條目保存到數據庫中?我嘗試了下面的代碼,但沒有插入到數據庫中。非常感謝:)Symfony2:堅持用戶輸入數據庫

/** 
 
    * @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

當您使用表單時,您正在填寫'$ quest'對象的詳細信息,但之後您將獲取存儲庫,然後嘗試將其保存到數據庫。如果你刪除'$ entity = $ em-> getRepository('IWABundle:quest');'而是將'$ quest'對象保存到數據庫中。 – qooplmao

回答

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 databasehow to manage form submission的官方文檔。