简体   繁体   中英

Symfony2: Submit data from a form in a twig template to database

I am rendering a form using Symfony2. At present my action method within my Controller renders a view containing a form:

/**
 * @Route("/hot", name="sort")
 * @Template()
 */
public function testAction(Request $request)
{
    $task = new enquiry();
    $form = $this->createForm(new QuestionType(), $task);

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

The part of my index.html.twig file which displays the forms looks like this:

{% block form %}
    <form action="{{ path('fake') }}">
        {{ form_start(form) }}
        {{ form_start(form.email) }}
        {{ form_start(form.firstname) }}
        {{ form_start(form.Enquiry) }}
        {{ form_end(form) }}
    </form>
{% endblock %}

How do you persist the User's input to the database using Twig. I have include an action in the form above to another controller to handle the form however it doesn't seem to work. If you know of a simple procedure to submit data once the use has clicked submit I would really appreciate if you could enlighten me.

Many thanks

By the time you typed this up you could have easily searched for the answer within the symfony2 documents.

Make sure your routers accepts both methods.

public function testAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $task = new enquiry();
    $form = $this->createForm(new QuestionType(), $task);
    $form->handleRequest($request);
    if ($form->isValid()) {
        $em->persist($task);
        $em->flush();
    }
    return $this->render('IWABundle:Default:index.html.twig', array('form'=>$form->createView()));

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM