2

I am having problems understanding the workflow how to insert some data in a table. So I have a simple contact form:

This is my form:

    {{ 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) }}

and this is my controller's function:

 /**
         * @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(),
                ));
            }
        }

I got all of the post request, but what should I do next, can you give me an example ? How can i write an insert query in Symfony ?

4
  • it depends. is Contact a Doctrine entity? (example here: symfony.com/doc/current/doctrine/…) Commented Nov 13, 2016 at 9:37
  • I have a Contact class in \AppBundle\Entity\Contact.php, I'm no really sure what is a Doctrine and how can use it ? Commented Nov 13, 2016 at 9:39
  • Also where is declare in which table the data will be inserted in your example ? Commented Nov 13, 2016 at 9:43
  • symfony has a good documentation, you can start from here. symfony.com/doc/current/doctrine.html Commented Nov 13, 2016 at 9:43

1 Answer 1

1

Usually, the favorite way to deal with such cases is to create a new entity (stored in AppBundle/Entity directory - which as I can understand, you already created it), and based on that entity, you need to create a new form (stored in AppBundle/Form directory).

Now, the problem with forms is that you can create them in several ways. One way is the one I've already told you; another way is to create it in the controller method, as you did.

To summarize, the following is just an example, using the first way, and using 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) }}

But please pay attention, as if you are using a symfony version < 2.8, then you should look here to see how to render text types (you'll need texttype, emailtype, and textareatype --- OR you can let them as they were generated, as is enough), but if you're using symfony >= 2.8, then all you need is to import, at the top of your ContactType class, the respective classes for each type you're using:

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

And, when building the form:

//...
$builder
    ->add('name',TextType::class)
    ->add('email',EmailType::class)
    ->add('website',TextType::class)
    ->add('comment',TextareaType::class)
;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.