2013-04-05 137 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..