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


How to insert data in the database in Symfony 3 issue

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

这是我的表单:

    {{ 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中编写插入查询?

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

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

总而言之,下面只是一个例子,使用第一种方式,并使用symfony>= 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版本<2.8,然后你应该看看这里看到如何渲染文本类型(你需要texttype, emailtype,和textareatype -或者你可以让他们,因为他们是生成的,就足够了),但如果你使用symfony>= 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)
;