2011-09-21 173 views
2

我有一个表单,用户输入数据。然后,当他们点击提交时,这些数据将被保存到数据库中。无法使用Symfony2中的表单将数据插入到数据库中

唯一的是,它不这样做。发生的情况是,当点击提交时,页面将重新加载,并且所有输入的数据仍然会显示。我去检查数据库,并且记录没有被更新。

没有错误,但根据探查器有三个SQL语句在页面加载时运行。所有这三个都是SELECT语句,而不是一个INSERT语句。

下面是控制器的页面(包括“插入”语句)代码:

public function addAction(Request $request) 
{ 

    $pageadd = new Content(); 
    $form = $this->createForm(new PageAdd(), $pageadd); 

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

     if ($form->isValid()) { 
      $em = $this->getDoctrine()->getEntityManager(); 

      $em->persist($pageadd); 
      $em->flush(); 

      return new Response('Created page id '.$pageadd->getId()); 

     } 
    } 

    return $this->render('ShoutAdminBundle:Default:pageadd.html.twig', array(
     'form' => $form->createView() 
    )); 

} 

下面是形式的代码(我省略了一些空间原因字段。但他们都是相同的):

<form action="{{ path('ShoutAdminBundle_adminpageaddpost') }}" method="post" {{ form_enctype(form) }} class="blogger"> 

    <p class="row"> 
     {{ form_label(form.id, 'ID*', { 'attr': {'class': 'title'} }) }} 
     {{ form_errors(form.id) }} 
     {{ form_widget(form.id, { 'attr': {'class': 'textfield'}}) }} 
    </p> 
    <p class="row"> 
     {{ form_label(form.title, 'Title*', { 'attr': {'class': 'title'} }) }} 
     {{ form_errors(form.title) }} 
     {{ form_widget(form.title, { 'attr': {'class': 'textfield'}}) }} 
    </p> 

    <p class="row"> 
     <input type="submit" value="Save This Page" class="savebutton" /> 
    </p> 
</form> 

如果您需要更多的代码,我会提供他们。我认为这两个代码是问题所在。

干杯!

回答

2

的坚持之前,必须填写的实体,我给你举个例子:

public function saveAction(Request $request) 
{ 
    if ($request->getMethod() == 'POST') { 
     // EntityManager 
     $em = $this->getDoctrine()->getEntityManager(); 

     // New entity 
     $registration = new Customer(); 

     // Build the form 
     $form = $this->createFormBuilder() 
     ->add('name', 'text') 
     ->add('country', 'text') 
     ->add('email', 'email') 
     ->add('certificate', 'text') 
     ->add('provider', 'entity', array(
       'class' => 'YourCustomBundle:Partner', 
     )) 
     ->getForm(); 

     // Populate 
     $form->bindRequest($request); 

     // Check 
     if($form->isValid()) { 
      // Fill the entity 
      $registration->setName($form['name']->getData()); 
      $registration->setCountry($form['country']->getData()); 
      $registration->setEmail($form['email']->getData()); 
      $registration->setCertificate($form['certificate']->getData()); 
      $registration->setProvider($form['provider']->getData()); 
      $em->persist($registration); 
      $em->flush(); 
     } 

    } 
    return $this->render('YourCustomBundle:Default:index.html.twig',array(
      'form' => $form->createView(), 
    )); 
} 
相关问题