将数据从表单插入数据库

时间:2013-04-05 13:37:07

标签: symfony symfony-2.1 symfony-forms

我想做的是下一步:

  1. 使用FormBuilder创建简单表单

  2. 提交表单时,将结果保存到特定用户的数据库中(基于其ID)

  3. 另外还有来自控制器的代码:

    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。

2 个答案:

答案 0 :(得分:0)

您可以将评级设置为用户实体,如此...

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

    // etc..

答案 1 :(得分: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
}