如何在Symfony 3问题中插入数据库中的数据

时间:2016-11-13 09:30:25

标签: php symfony

我在理解如何在表格中插入一些数据的工作流程时遇到问题。所以我有一个简单的联系表格:

这是我的表格:

    {{ form_start(form, {
                        'attr': {'id': 'contact-form'},
                        'action': path('contact'), 'method': 'POST'}
                        )
                }}
                    <div class="text-fields">
                        <div class="float-input">
                            <input name="name" id="name" placeholder="Name" type="text">
                            <span><i class="fa fa-user"></i></span>
                        </div>
                        <div class="float-input">
                            <input name="mail" id="mail" placeholder="e-mail" type="text">
                            <span><i class="fa fa-envelope-o"></i></span>
                        </div>
                        <div class="float-input">
                            <input name="website" id="website" placeholder="website" type="text">
                            <span><i class="fa fa-link"></i></span>
                        </div>
                    </div>
                    <div class="comment-area">
                        <textarea name="comment" id="comment" placeholder="Message"></textarea>
                    </div>
                    <div class="submit-area">
                        <input type="submit" value="Send"/>
                    </div>
                    <div id="msg" class="message"></div>
  {{ form_end(form) }}

这是我的控制器功能:

 /**
         * @Route("/contact/", name="contact").
         */
        public function indexAction()
        {
            $contact = new Contact();

            $form = $this->createFormBuilder($contact)
                ->setAction($this->generateUrl('contact'))
                ->getForm();

            $request = Request::createFromGlobals();

            if ($request->isMethod('POST')) {
                $params = $request->request->all();
                var_dump($params); exit();
/// what should I do next here ?
            }else {
                return $this->render('contact/content.html.twig', array(
                    'form' => $form->createView(),
                ));
            }
        }

我得到了所有的帖子请求,但接下来我该怎么办,你能举个例子吗?如何在Symfony中编写插入查询?

1 个答案:

答案 0 :(得分:1)

通常,处理此类情况的最佳方式是创建一个新实体(存储在AppBundle/Entity目录中 - 据我所知,您已创建它),并且基于该实体,您需要创建一个新表单(存储在AppBundle/Form目录中)。

现在,表单的问题在于您可以通过多种方式创建它们。一种方式是我已经告诉过你的那种方式;另一种方法是在控制器方法中创建它,就像你一样。

总结一下,以下只是一个例子,使用第一种方式,并使用symfony&gt; = 2.8:

//1. Create an Entity class, using a symfony console command (after completing all steps, you'll end with the directory AppBundle/Entity and inside it a new php file Contact.php):
$ php app/console doctrine:generate:entity //and follow the interactive steps, and let's say you need the following columns: name (varchar:255), email (varchar:255), website (varchar:255), and comment (varchar:255).

//2. Create a new Form, based on that Entity class (after completing all steps, you'll end with the directory AppBundle/Form and inside it a new php file ContactType.php):
$ php app/console doctrine:generate:form AppBundle:Contact

//3. In the controller method:
use AppBundle\Entity\Contact;
use AppBundle\Form\ContactType;
//...
/**
 * @Route("/contact/", name="contact")
 * @Method({"GET","POST"})
 */
public function contactAction(Request $request){
    $contact = new Contact();

    //for symfony >= 2.8
    $form = $this->createForm(ContactType::class, $contact, [

    //or if you're using symfony < 2.8, replace the above line with this:
    $form = $this->createForm(ContactType, $contact, [
        'action'=>$this->generateUrl('contact'),
        'method'=>'POST'
    ]);
    $form->handleRequest($request);
    if($form->isSubmitted() && $form->isValid()){
        //...more stuff pre-insertion here if needed
        $em = $this->getDoctrine()->getManager();
        $em->persist($contact);//persist the contact object
        $em->flush();//save it to the db
        //...more stuff post-insertion here if needed
        return $this->redirectToRoute('homepage');
    }
    return $this->render('contact/content.html.twig', array(
        'form' => $form->createView(),
    ));
}

//4. In contact/contact.html.twig:
{{ form_start(form) }}
    <div class="text-fields">
        <div class="float-input">
            {{ form_row(form.name,{ attr:{ name:'name',id:'name',placeholder:'Name' } }) }}
            <span><i class="fa fa-user"></i></span>
        </div>
        <div class="float-input">
            {{ form_row(form.email,{ attr:{ name:'email',id:'email',placeholder:'e-mail' } }) }}
            <span><i class="fa fa-envelope-o"></i></span>
        </div>
        <div class="float-input">
            {{ form_row(form.website,{ attr:{ name:'website',id:'website',placeholder:'website' } }) }}
            <span><i class="fa fa-link"></i></span>
        </div>
    </div>
    <div class="comment-area">
        {{ form_row(form.comment,{ attr:{ name:'comment',id:'comment',placeholder:'Message' } }) }}
    </div>
    <div class="submit-area">
        <input type="submit" value="Send"/>
    </div>
    <div id="msg" class="message"></div>
{{ form_end(form) }}

但请注意,好像您使用的是symfony版本&lt; 2.8,然后你应该看here看看如何渲染文本类型(你需要texttype,emailtype和textareatype ---或者你可以让它们生成,就像它们一样),但如果你'使用symfony&gt; = 2.8,那么您只需要在ContactType类的顶部导入您正在使用的每种类型的相应类:

use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;

并且,在构建表单时:

//...
$builder
    ->add('name',TextType::class)
    ->add('email',EmailType::class)
    ->add('website',TextType::class)
    ->add('comment',TextareaType::class)
;