2013-04-05 134 views
1

下一個就是我想要做的是:插入數據到數據庫

  1. 與FormBuilder

  2. 當表單提交的結果創建簡單的形式被保存到數據庫中的特定用戶(基於它的ID)

另外是來自控制器的代碼:

public function helloAction(Request $request, $id){//displaying individual results for particular user// 


// find the username which was in the view// 

    $em = $this->getDoctrine()->getManager(); 
     $query = $em->createQuery('SELECT b FROM AcmeWebBundle:baza b WHERE b.id = :id') 
     ->setParameter('id',$id); 
     $total = $query->getResult(); 

$baza = new baza(); 

    $em = $this->getDoctrine()->getManager(); 
     $em->persist($baza); 
     $form = $this->createFormBuilder($baza) 
        ->add ('rating','choice',array('label'=>'TEST44','choices'=>array(
         '1'=>'1', 
         '2'=>'2', 
         '3'=>'3', 
         '4'=>'4' 
         ), 

        'expanded'=>true, 
        'multiple'=>false 
        )) 
        ->getForm(); 


     if ($request->getMethod() == 'POST') { 
      $form->bindRequest($request); 

      if ($form->isValid()) { 
       // perform some action, such as saving the task to the database 
       $em->flush(); 

       return new Response('<h1>THANKS FOR Your feedback !!!!</h1>'); 

      } 


     } 


return $this->render('AcmeWebBundle:Default:hello.html.twig',array('all'=>$total,'id'=>$id ,'form'=>$form->createView())); 
} 
} 

但是這會在數據庫中創建新行,並且只爲評級列添加值。此外,id字段,用戶名等等是空的。

我想要做的是,額定值要添加爲列的評級,但爲特定的ID。

+0

你是否對每個GET請求調用'$ em-> persist($ baza)'?你必須清理你的思想,重新組織你的想法。 – 2013-04-05 14:22:03

回答

0

在下面的例子中,我創建的形式,得到POST的數據,然後堅持新鮮的對象或修改之一,有堅持一個空洞的對象是沒有意義的。

public function historialAction(Request $request) 
{ 
$form = $this->createFormBuilder() 
->add('phone', 'text', array('attr' => array('autofocus' => ''))) 
->add('period', 'number', array('attr' => array('value' => '12'))) 
->getForm(); 

if ($request->isMethod('POST')) { 
    $form->bind($request); 

    // data is an array with "phone" and "period" keys 
    $data = $form->getData(); 

    $em = $this->getDoctrine()->getManager(); 

    $contract = $em->getRepository('FrontBundle:Contract')->getContractByPhone($data["phone"]); 
    $contract->setOwner("John Doe"); 
    $contract->setPhone($data["phone"]); 

    // or this could be $contract = new Contract("John Doe", $data["phone"], $data["period"]); 


    $em->persist($contract); // I set/modify the properties then persist 
} 
0

您可以在等級設置爲像這樣用戶實體..

if ($form->isValid()) 
    $rating = $form->get('rating')->getData(); 
    $user->setRating($rating); 
    // Assuming $user is the user entity 

    // etc..